A reference (&) lets a function read a value without taking ownership, so the caller keeps using it afterward.

Program

Play the program to borrow message inside word_count and still print it.

borrowing.rs
Replay: real traced execution (multi-file project)
fn main() {
    let message = String::from("borrow me");
    let length = word_count(&message);
    println!("{message} has {length}");
}

fn word_count(text: &str) -> usize {
    text.split_whitespace().count()
}
  1. message ← "borrow me"

    1fn main() {2    let messag→ "borrow me"e = String::from("borrow me");3    let length = word_count(&messag"borrow me"e);4    println!("{message} has {length}");
  2. length ← 2

    2    let message = String::from("borrow me");3    let lengt→ 2h = word_count(&messag"borrow me"e);4    println!("{message} has {length}");5}
    outputborrow me has 2

Follow the Borrow

  1. message owns the string in main.
  2. &message lends a read-only view to word_count.
  3. word_count reads the words and returns a number.
  4. main still owns message, so it can print it afterward. | Moment | Who can read message? | | --- | --- | | Before the call | main | | During the call | word_count through &message | | After the call | main again |
reference `&message` borrows the value instead of moving it.
no ownership transfer `message` is still valid after the call.
split_whitespace `split_whitespace().count()` counts the words.

Exercise: borrowing.rs

Pass one String by shared reference to two read-only helpers, then print the original String