In the last lesson, a function that took a String parameter had to return it, or the caller lost the text. Most functions only need to look at a value: print it, measure it, compare it. For that, Rust lets you lend a value instead of handing it over. A reference is a way to access a value owned somewhere else. Writing &title creates a reference to title; this is called borrowing. The owner stays the same, so nothing moves and nothing is released when the function ends.
For text, the usual reference type is &str, pronounced "string slice": a read-only view of some text. A string literal such as "Rust" already has type &str. When you pass &title where title is a String, Rust converts the &String into a &str view of the same text automatically.
Predict and run
Will the second line be able to use title after the function returns?
fn show(topic: &str) {
println!("Next: {topic}");
}
fn main() {
let title = String::from("Borrowing");
show(&title);
println!("Still yours: {title}");
}Check your prediction
Next: Borrowing
Still yours: Borrowingshow borrowed the text for the length of the call. When the call ended, the borrow ended too, and main still owned title. Compare this with announce in the previous lesson: no return value was needed. Now add the call show("Loops"); and predict its output. The literal can be passed directly, because it is already a &str.
Why the parameter is &str, not &String
You could also write the parameter as &String. That accepts &title, but it rejects literals:
fn show(topic: &String) {
println!("{topic}");
}
fn main() {
show("Loops");
}This fails with error[E0308]: mismatched types, expected &String, found &str. A &str parameter accepts both kinds of text, so it is the better choice whenever a function only reads.
fn describe(topic: &str) -> usize {
println!("{topic} has {} letters", topic.len());
topic.len()
}
fn main() {
let title = String::from("Borrowing");
let first = describe(&title);
let second = describe("Loops");
println!("Together: {}", first + second);
println!("Owner: {title}");
}Borrowing has 9 letters
Loops has 5 letters
Together: 14
Owner: Borrowinglen returns a usize, the unsigned integer type Rust uses for sizes and counts. Strictly speaking it counts bytes, which equals the number of letters for plain English text like this. The function borrows the text, reads it and returns a number, while main keeps ownership throughout.
A shared borrow cannot change the text
There are two common mistakes with borrows. The first is forgetting the & at the call:
fn show(topic: &str) {
println!("{topic}");
}
fn main() {
let title = String::from("Borrowing");
show(title);
}This fails with error[E0308]: mismatched types, expected &str, found String, and the compiler suggests consider borrowing here. Without the &, you would be trying to give the String away, and the function did not ask for that.
The second is trying to change borrowed text. A &str is a read-only view, so a function that calls topic.push_str("!") on it fails with error[E0599]: no method named push_str found for reference &str. Read access is all a shared borrow grants. The next lesson shows the kind of borrow that can change a String.
Default to borrowing
When you write a function that takes text, start with &str. Take a String only when the function needs to keep the text, for example to store it.
Practice
Your turn
Write receipt to accept a borrowed topic and a number of minutes. It should print Practice: 15 min. Call it with the String from the starter, then call it again with the literal "Review" and 10. Finally, show from main that the original String is still available by printing Saved: Practice.
fn main() {
let title = String::from("Practice");
// Call your receipt function here.
println!("Saved: {title}");
}Hint 1: the idea
The function only reads the title, so its parameter can be a shared text slice. Then the same function accepts both the String and the literal.
Hint 2: a first step
Define fn receipt(topic: &str, minutes: i32) above main, and call it with receipt(&title, 15);.
Worked solution
fn receipt(topic: &str, minutes: i32) {
println!("{topic}: {minutes} min");
}
fn main() {
let title = String::from("Practice");
receipt(&title, 15);
receipt("Review", 10);
println!("Saved: {title}");
}Practice: 15 min
Review: 10 min
Saved: PracticeThe ampersand at the first call borrows the title for the duration of that call, and the literal needs no ampersand because it is a &str already. If you change the parameter to &String, the second call stops compiling. Next you give a function permission to change the caller's String.
Completion is saved in this browser only. It does not measure mastery.