Ownership and Borrowing
Borrowing
Reading Without Owning
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()
}
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}");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
messageowns the string inmain.&messagelends a read-only view toword_count.word_countreads the words and returns a number.mainstill ownsmessage, so it can print it afterward. | Moment | Who can readmessage? | | --- | --- | | Before the call |main| | During the call |word_countthrough&message| | After the call |mainagain |
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