1. Ownership — RuSt’s superpower
Rules:
- Every value has a single owner.
- Only one owner at a time.
- When the owner goes out of scope, the value is dropped (freed) automatically.
let s1 = String::from("hello");
let s2 = s1; // s1 MOVES to s2 — s1 is no longer valid
// println!("{s1}"); // compile error: use of moved value
- Moving is the default for heap types; no double-free because ownership guarantees one owner.
- Copy types (
i32,bool,char, tuples of them) areCopy— assignment duplicates.
2. Borrowing
- References let you access a value without taking ownership:
&x(immutable),&mut x(mutable).
fn len(s: &String) -> usize { s.len() }
let s = String::from("hi");
let r1 = &s; // immutable borrow
let r2 = &s; // many immutable borrows OK
Rules:
- At any moment: either any number of immutable borrows or one mutable borrow.
- References must always be valid (no dangling references — compile-time enforced).
let mut x = 5;
let a = &x; let b = &x; // OK — shared reads
let c = &mut x; // compile error while a,b alive
3. Lifetimes
- Lifetimes are the compiler’s way of guaranteeing references stay valid.
- Most are inferred; annotate when references relate across inputs/outputs.
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
'a= “both inputs must live at least as long as the return borrow”.- Lifetime elision rules cover the common cases (single input → same for output).
4. ‘static
'static= lives for the whole program.- String literals
&'static str, consts, statics. - Don’t panic about
'staticin aBox<dyn ...>age question — it often just means “owned, no borrows”.
5. Interview checkpoint
- Ownership vs borrowing mental model; move semantics.
- Why no double-free / use-after-free.
&vs&mutexclusivity rule.- Lifetime annotations on function signatures.
- Copy types vs move types.
Premium Content
Unlock Part 1: Ownership, Borrowing & Lifetimes and all premium lessons with a subscription.
All premium lessons
Ad-free experience
Priority support
From ₹199.99/year — See plans