References and Borrowing

Borrowing allows you to use a value without taking ownership.

Immutable References

let s = String::from("hello");
let len = calculate_length(&s);

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

&s passes a reference, not ownership.

Mutable References

let mut s = String::from("hello");
change(&mut s);

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

Only one mutable reference allowed at a time to avoid data races.

← PrevNext →