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
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()
}
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.