Rust Borrowing and References

Borrowing values without taking ownership

Immutable References

let s1 = String::from("hello");
let len = calculate_length(&s1); # borrow s1
println!("{}"{}, s1, len); # s1 still valid
fn calculate_length(s: &String) -> usize { # reference parameter
    s.len() # doesn't take ownership
}

Mutable References

let mut s = String::from("hello");
change(&mut s); # mutable borrow
fn change(s: &mut String) { # mutable reference
    s.push_str(" world"); # can modify
}

Borrowing Rules

# 1. One mutable reference OR
# 2. Any number of immutable references
# 3. References must always be valid
let mut s = String::from("hello");
let r1 = &s; # ok
let r2 = &s; # ok
// let r3 = &mut s; // ERROR: cannot borrow as mutable

Slice References

let s = String::from("hello world");
let hello = &s[0..5]; # slice reference
let world = &s[6..11]; # another slice