rust-ownership-system
БесплатноБез исполняемых скриптовНе проверенUse when Rust's ownership system including ownership rules, borrowing, lifetimes, and memory safety. Use when working with Rust memory management.
от TheBushidoCollective★ 202 звезды на GitHubОб этом скилле
Rust Ownership System
Master Rust's unique ownership system that provides memory safety without garbage collection through compile-time checks.
Ownership Rules
Three fundamental ownership rules:
- Each value in Rust has a variable that's its owner
- There can only be one owner at a time
- When the owner goes out of scope, the value is dropped
fn ownership_basics() {
// s owns the String
let s = String::from("hello");
// Ownership moved to s2
let s2 = s;
// Error: s no longer owns the value
// println!("{}", s);
println!("{}", s2); // OK
} // s2 dropped here, memory freed
Move Semantics
Ownership transfer (move):
fn move_semantics() {
let s1 = String::from("hello");
// Ownership moved to function
takes_ownership(s1);
// Error: s1 no longer valid
// println!("{}", s1);
}
fn takes_ownership(s: String) {
println!("{}", s);
} // s dropped here
// Return ownership from function
fn gives_ownership() -> String {
String::from("hello")
}
fn main() {
let s = gives_ownership();
println!("{}", s);
}
Copy trait for stack types:
fn copy_types() {
// Types implementing Copy are duplicated, not moved
let x = 5;
let y = x; // x copied to y
println!("x: {}, y: {}", x, y); // Both valid
// Copy types: integers, floats, bool, char, tuples of Copy types
let tuple = (1, 2.5, true);
let tuple2 = tuple;
println!("{:?} {:?}", tuple, tuple2); // Both valid
}
Borrowing
Immutable borrowing (references):
fn immutable_borrow() {
let s1 = String::from("hello");
// Borrow s1 (immutable reference)
let len = calculate_length(&s1);
println!("Length of '{}' is {}", s1, len); // s1 still valid
}
fn calculate_length(s: &String) -> usize {
s.len()
} // s goes out of scope, but doesn't drop the value
// Multiple immutable borrows allowed
fn multiple_immutable_borrows() {
let s = String::from("hello");
let r1 = &s;
let r2 = &s;
let r3 = &s;
println!("{}, {}, {}", r1, r2, r3); // OK
}
Mutable borrowing:
fn mutable_borrow() {
let mut s = String::from("hello");
// Mutable borrow
change(&mut s);
println!("{}", s); // "hello, world"
}
fn change(s: &mut String) {
s.push_str(", world");
}
// Only ONE mutable borrow allowed at a time
fn mutable_borrow_rules() {
let mut s = String::from("hello");
let r1 = &mut s;
// let r2 = &mut s; // Error: cannot borrow mutably twice
println!("{}", r1);
}
// Cannot mix mutable and immutable borrows
fn no_mix_borrows() {
let mut s = String::from("hello");
let r1 = &s; // Immutable borrow
let r2 = &s; // Another immutable borrow
// let r3 = &mut s; // Error: cannot borrow mutably while immutably borrowed
println!("{} {}", r1, r2);
}
Non-lexical lifetimes (NLL):
fn non_lexical_lifetimes() {
let mut s = String::from("hello");
let r1 = &s;
let r2 = &s;
println!("{} {}", r1, r2);
// r1 and r2 no longer used after this point
// OK: immutable borrows ended
let r3 = &mut s;
println!("{}", r3);
}
Lifetimes
Lifetime annotations:
// Lifetime 'a ensures returned reference lives as long as both inputs
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
fn main() {
let string1 = String::from("long string");
let string2 = String::from("short");
let result = longest(&string1, &string2);
println!("Longest: {}", result);
}
Lifetime in structs:
// Struct holds a reference, needs lifetime annotation
struct ImportantExcerpt<'a> {
part: &'a str,
}
impl<'a> ImportantExcerpt<'a> {
fn level(&self) -> i32 {
3
}
fn announce_and_return_part(&self, announcement: &str) -> &str {
println!("Attention: {}", announcement);
self.part
}
}
fn main() {
let novel = String::from("Call me Ishmael. Some years ago...");
let first_sentence = novel.split('.').next().unwrap();
let excerpt = ImportantExcerpt {
part: first_sentence,
};
println!("{}", excerpt.part);
}
Lifetime elision rules:
// Compiler infers lifetimes in these cases:
// Rule 1: Each reference parameter gets its own lifetime
fn first_word(s: &str) -> &str {
// Expanded: fn first_word<'a>(s: &'a str) -> &'a str
s.split_whitespace().next().unwrap_or("")
}
// Rule 2: If one input lifetime, assign to all outputs
fn foo(s: &str) -> &str {
s
}
// Rule 3: If &self or &mut self, its lifetime assigned to outputs
impl<'a> ImportantExcerpt<'a> {
fn get_part(&self) -> &str {
// Expanded: fn get_part<'a>(&'a self) -> &'a str
self.part
}
}
Static lifetime:
// 'static means reference lives for entire program duration
fn static_lifetime() -> &'static str {
"This stri
Установить rust-ownership-system в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
BashReadFAQ
Что делает скилл rust-ownership-system?
Use when Rust's ownership system including ownership rules, borrowing, lifetimes, and memory safety. Use when working with Rust memory management.
Как установить скилл rust-ownership-system?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл rust-ownership-system запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic