Borrowing

View saved

Immutable borrows

&T lets you read without taking ownership. Many immutable borrows may exist at once.

fn len(s: &String) -> usize {
    s.len()
}

fn main() {
    let s = String::from("rust");
    println!("{}", len(&s));
    println!("{s}");
}

Mutable borrows

&mut T allows modification. Only one mutable borrow may be active.

fn push_world(s: &mut String) {
    s.push_str(" world");
}

let mut s = String::from("hello");
push_world(&mut s);
println!("{s}");

Borrow checker intent

References must not outlive the data they point to. The compiler rejects dangling references.

Borrowing habits

  • Prefer &str parameters when you only need to read text
  • Keep mutable borrows short
  • Do not mix mutable and immutable borrows of the same value at the same time
  • Compiler errors about borrows are common—read the noted scopes

Comments

One comment per signed-in account. Comments are saved with this page’s URL.