Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Reference & Borrowing

Reference

  • Allow to refer to the value without the change in the ownership -> reference borrows the value
  • References are immutable by default unless mut is used
  • Reference is guaranteed to point to a valid value of a particular type for the life of that reference
fn main() {
    let s1 = String::from("hello");

    // due to reference s1 will not be dropped after the function call
    let len = calculate_length(&s1);

    println!("The length of '{s1}' is {len}.");
}

// we can pass a reference to a function as a parameter, String ownership is not transferred
fn calculate_length(s: &String) -> usize {
    s.len()
}

Mutable reference

  • Reference can be mutable with mut
  • At a any point in time:
    • just one mutable reference can exist or
    • one or more immutable references can exist
fn main() {
    let mut s = String::from("hello");

    change(&mut s);
}

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

Dangling reference

  • Prevented by Rust compiler
fn main() {

    // will return error as there is no value to borrow from 
    let reference_to_nothing = dangle();
}

fn dangle() -> &String {
    let s = String::from("hello");

    &s
}