| name | ownership-borrowing |
| description | Master Rust's ownership, borrowing, and lifetime system. Use when working with move semantics, references, lifetimes, or memory safety patterns. |
Ownership & Borrowing Skill
Master Rust's revolutionary memory safety system without garbage collection.
Quick Start
The Three Rules of Ownership
let s1 = String::from("hello");
let s2 = s1;
{
let s3 = String::from("temporary");
}
Borrowing Basics
fn main() {
let s = String::from("hello");
let len = calculate_length(&s);
println!("{} has length {}", s, len);
let mut s = String::from("hello");
change(&mut s);
println!("{}", s);
}
fn calculate_length(s: &String) -> usize {
s.len()
}
fn change(s: &mut String) {
s.push_str(", world");
}
Lifetime Annotations
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
struct Excerpt<'a> {
part: &'a str,
}
Common Patterns
Pattern 1: Clone When Needed
let s1 = String::from("hello");
let s2 = s1.clone();
println!("{} {}", s1, s2);
Pattern 2: Return Ownership
fn process(s: String) -> String {
s
}
Pattern 3: Borrow for Read-Only
fn analyze(data: &Vec<Data>) -> Summary {
Summary::from(data)
}
Error Solutions
"value borrowed after move"
let s = String::from("hello");
let s2 = s;
println!("{}", s);
let s2 = s.clone();
let s2 = &s;
"cannot borrow as mutable"
let s = String::from("hello");
change(&mut s);
let mut s = String::from("hello");
change(&mut s);
Resources