Skip to content
Rust

Borrowing and References

References and mutable borrows.

By EZ4Code Team
borrowreference

Code

fn main() {
    let s = String::from("hello");

    // Immutable reference
    let len = calculate_length(&s);
    println!("'{}' length is {}", s, len);

    // Mutable reference
    let mut s2 = String::from("hello");
    change(&mut s2);
    println!("{}", s2);

    // Multiple immutable references
    let r1 = &s2;
    let r2 = &s2;
    println!("{} {}", r1, r2);

    // Slice reference
    let hello = &s2[0..5];
    println!("{}", hello);
}

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

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

Explanation

Borrowing allows referencing values without taking ownership; only one mutable reference or multiple immutable references at a time.

More Rust Snippets