Sub topic 12
Borrow, move, or clone: choosing a parameter type
This chapter assumes you know shared and mutable references, the "many readers or one writer" rule, and basic String, Vec, and &str usage. Here you will decide which type a function parameter should have.
The three choices
Every parameter forces a choice about ownership.
| Parameter type | What the caller gives up | Use it when the function... |
|---|---|---|
| `&T` | Nothing | only reads the value |
| `&mut T` | Exclusive access during the call | changes the caller's value in place |
| `T` | Ownership (a move) | stores, returns, or consumes the value |
Cloning is not a parameter type. It is something the caller or the function does to get a second owned value when ownership is needed but the original must survive.
Start with the weakest access
Pick the least powerful option that works. A shared reference lets the caller keep using the value and lets many callers share it. Move up to &mut T or T only when the function needs more.
fn word_count(text: &str) -> usize {
text.split_whitespace().count()
}
fn shout(text: &mut String) {
text.make_ascii_uppercase();
}
fn into_title(name: String) -> String {
format!("Dr. {name}")
}
fn main() {
let mut note = String::from("borrowing is useful");
println!("{}", word_count(¬e));
shout(&mut note);
println!("{note}");
let name = String::from("Rivera");
let title = into_title(name.clone());
println!("{title} and {name}");
}into_title takes ownership because it builds a new String from its input. The caller passes name.clone() because name is used again on the last line. Without the clone, that line would fail with a "borrow of moved value" error.
Prefer borrowed views in signatures
For read-only parameters, take the slice type, not a reference to the owning type.
- Use
&strinstead of&String. - Use
&[T]instead of&Vec<T>.
A &String coerces to &str, and a &Vec<T> coerces to &[T], so the slice version accepts more callers. It also accepts string literals and arrays, which &String and &Vec<T> do not.
fn total(values: &[i32]) -> i32 {
values.iter().sum()
}
fn main() {
let v = vec![1, 2, 3];
let arr = [4, 5, 6];
println!("{} {}", total(&v), total(&arr));
}When to take ownership
Take T by value when the function keeps the data. Typical cases are storing it in a struct, pushing it into a collection, or sending it to another thread. Taking &str and calling .to_string() inside would also work, but it hides an allocation from the caller. A by-value String parameter makes the cost visible and lets callers who already own a String pass it without copying.
struct User {
name: String,
}
impl User {
fn new(name: String) -> User {
User { name }
}
}
fn main() {
let user = User::new(String::from("Ana"));
println!("{}", user.name);
}When to clone
Clone when you need two independent owners and borrowing cannot express it. For example, the data must outlive the original, or a lifetime would make the API awkward. Cloning a String or Vec allocates and copies, so avoid it in hot loops. Treat a clone added only to silence the borrow checker as a signal to rethink the design.
Exercise
A function fn tag(label: ???) -> Tag builds a Tag struct that stores the label. The caller still needs its own String afterwards. What should the parameter type be, and what does the caller write?
Show answer
Use label: String, because the struct stores the label and so needs ownership. The caller passes my_label.clone() to keep its original. A &str parameter that clones inside would also work, but then the function hides the allocation.