Tsallaka zuwa abun ciki
Justice Tech School

References and Borrowing Rules

& borrows immutably and &mut borrows mutably. You may have many shared references or exactly one mutable reference at a time, and references must never outlive their data.

Example
fn len(s: &String) -> usize { s.len() }
fn append(s: &mut String) { s.push_str("!"); }
fn main() {
    let mut s = String::from("hi");
    println!("{}", len(&s));
    append(&mut s);
    println!("{}", s);
}

Result

2
hi!

Exercise

Mutable borrow.

& s

Quiz Test

How many mutable references at once?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.