Ownership & Borrowing in Rust

From the Rust cheat sheet · Ownership & Borrowing · verified Jul 2026

Ownership & Borrowing

Move semantics, borrowing rules, and the Clone/Copy distinction.

rust
// Ownership — each value has one owner
let s1 = String::from("hello");
let s2 = s1;          // s1 is MOVED to s2, s1 is no longer valid
// println!("{s1}");   // ERROR: value moved

// Clone — explicit deep copy
let s1 = String::from("hello");
let s2 = s1.clone();  // Deep copy, both valid

// Borrowing — references don't take ownership
fn print_len(s: &String) { println!("{}", s.len()); }
print_len(&s2);        // Borrow s2, s2 still valid

// Mutable reference
fn push_world(s: &mut String) { s.push_str(" world"); }
💡 Copy types (i32, f64, bool, char) are copied on assignment; heap types (String, Vec) are moved
⚡ The rule: either one &mut OR many & — never both at the same time
📌 When a function takes a value (not a reference), ownership is moved and the caller loses it
🟢 Use .clone() when you need two owners — but prefer borrowing when possible
ownershipborrowingreferencesmoveclone
Back to the full Rust cheat sheet