Menu

Earn Premium with Referrals

Invite your friends and earn Premium rewards through our referral program.

See how it works and start inviting friends.

Part 1: Ownership, Borrowing & Lifetimes
RUST

Part 1: Ownership, Borrowing & Lifetimes

Revise Rust ownership rules, borrowing, references, lifetimes, and the borrow checker's role in memory safety.

1. Ownership — RuSt’s superpower

Rules:

  1. Every value has a single owner.
  2. Only one owner at a time.
  3. 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) are Copy — 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:

  1. At any moment: either any number of immutable borrows or one mutable borrow.
  2. 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 'static in a Box<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 &mut exclusivity rule.
  • Lifetime annotations on function signatures.
  • Copy types vs move types.

My Private Notes

Notes are auto-saved locally to this device.