Skip to content
Justice Tech School

Borrowing and References

& borrows without taking ownership and &mut allows changes. One mutable borrow or many shared ones at a time.

Example
fn len(s: &String) -> usize { s.len() }
fn add(s: &mut String) { s.push_str("!"); }

fn main() {
    let mut s = String::from("hi");
    let n = len(&s);
    add(&mut s);
    println!("{} {}", s, n);
}

Result

hi! 2

Exercise

Mutable borrow.

& s

Quiz Test

How many &mut at once?

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