rust-ownership
Master Rust ownership, borrowing, lifetimes, and memory safety. Understand move semantics, references, and zero-cost abstractions.
When & Why to Use This Skill
This Claude skill provides a deep-dive educational framework for mastering the Rust ownership system, the language's most critical and challenging concept. It helps developers achieve memory safety and high performance by demystifying borrowing rules, lifetimes, and move semantics, effectively bridging the gap between beginner syntax and professional-grade systems programming.
Use Cases
- Resolving Borrow Checker Conflicts: Providing step-by-step explanations and fixes when the Rust compiler rejects code due to ownership or borrowing violations.
- Designing Memory-Safe Architectures: Guiding developers on when to use references, smart pointers (Box, Rc, Arc), or ownership transfers to optimize resource management.
- Mastering Lifetime Annotations: Helping programmers understand and implement explicit lifetime parameters in complex functions and data structures to ensure reference validity.
- Performance Optimization: Teaching how to leverage zero-cost abstractions and move semantics to write efficient code that performs at C++ levels without a garbage collector.
| name | rust-ownership |
|---|---|
| description | Master Rust ownership, borrowing, lifetimes, and memory safety. Understand move semantics, references, and zero-cost abstractions. |
Rust Ownership System
Master Rust's ownership system for writing safe, efficient, and concurrent code without garbage collection.
Core Concepts
Ownership Rules
- Each value has an owner
- Only one owner at a time
- Value dropped when owner goes out of scope
fn main() {
let s1 = String::from("hello");
let s2 = s1; // s1 moved to s2, s1 no longer valid
println!("{}", s2); // OK
// println!("{}", s1); // Error: value borrowed after move
}
Borrowing
fn main() {
let s1 = String::from("hello");
let len = calculate_length(&s1); // Borrow s1
println!("Length of '{}' is {}", s1, len); // s1 still valid
}
fn calculate_length(s: &String) -> usize {
s.len()
} // s goes out of scope but nothing happens (doesn't own the data)
Mutable References
fn main() {
let mut s = String::from("hello");
change(&mut s);
println!("{}", s); // "hello, world"
}
fn change(s: &mut String) {
s.push_str(", world");
}
Lifetimes
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
Best Practices
- Prefer borrowing over ownership transfer
- Use mutable references sparingly
- Understand lifetime elision rules
- Use smart pointers (Box, Rc, Arc) when needed
- Leverage the borrow checker