HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustModeratepending

Rust ownership and borrowing cheat sheet

Submitted by: @anonymous··
0
Viewed 0 times
ownershipborrowingmove semanticsmutable borrowlifetimerust basics

Problem

Need a quick reference for Rust's ownership rules, borrowing, and common patterns.

Solution

Rust ownership and borrowing essentials:

// RULE 1: Each value has exactly one owner
let s1 = String::from("hello");
let s2 = s1;  // s1 is MOVED to s2
// println!("{s1}");  // Error! s1 is no longer valid

// Clone to keep both
let s1 = String::from("hello");
let s2 = s1.clone();  // Deep copy
println!("{s1} {s2}");  // Both valid

// RULE 2: Immutable borrows (&T) - unlimited readers
let s = String::from("hello");
let r1 = &s;  // OK
let r2 = &s;  // OK - multiple immutable borrows
println!("{r1} {r2}");

// RULE 3: Mutable borrow (&mut T) - exclusive writer
let mut s = String::from("hello");
let r = &mut s;  // OK - one mutable borrow
// let r2 = &mut s;  // Error! Can't have two &mut
// let r3 = &s;      // Error! Can't mix & and &mut
r.push_str(" world");

// COMMON PATTERNS:

// Functions that read (borrow immutably)
fn length(s: &str) -> usize {
    s.len()  // Borrows, doesn't own
}

// Functions that modify (borrow mutably)
fn append(s: &mut String, suffix: &str) {
    s.push_str(suffix);
}

// Functions that consume (take ownership)
fn consume(s: String) {
    println!("{s}");  // s is dropped at end of function
}

// Return ownership
fn create() -> String {
    String::from("new")  // Ownership moves to caller
}

// Iterating without consuming
let v = vec![1, 2, 3];
for x in &v { /* borrows */ }
for x in &mut v { /* borrows mutably */ }
for x in v { /* consumes v! */ }

// Common fix: .iter() instead of into_iter()
let v = vec![1, 2, 3];
let sum: i32 = v.iter().sum();  // Borrows
println!("{:?}", v);  // v still usable

Why

Ownership is Rust's core innovation - it guarantees memory safety without garbage collection. Understanding these three rules (one owner, many &, exclusive &mut) is essential for writing Rust.

Context

Learning and writing Rust

Revisions (0)

No revisions yet.