Sub topic 12
Borrow, move, or clone: choosing a parameter type
This chapter assumes you know the move rules, shared references (&T), mutable references (&mut T), the "many readers or one writer" rule, and the lifetime elision rules. Here you will use them to decide what type a function parameter should have.
Every function signature answers one question for the caller: what happens to my value when I call you? The parameter type is the answer. Picking it well keeps callers' code simple and avoids needless copies.
The four choices
| Parameter type | Caller keeps the value? | Function can modify it? | Typical use |
|---|---|---|---|
| `&T` | Yes | No | Read, inspect, compute |
| `&mut T` | Yes, after the call | Yes, in place | Update caller's data |
| `T` (move) | No | Yes (it owns it) | Store, consume, transform |
| `T` after `.clone()` | Yes, with a separate copy | Either | Independent copy needed |
Start from the weakest access that does the job. Read-only access is the weakest, so try &T first. Move up to &mut T or T only when the function needs more.
Default to a shared borrow
If a function only reads, borrow. The caller keeps ownership and nothing is copied.
For text and sequences, prefer the slice types &str and &[T] over &String and &Vec<T>. A &String argument rejects string literals and slices of other strings. A &str accepts all of them, because &String coerces to &str automatically (this is called deref coercion). The same holds for &Vec<T> and &[T].
fn count_words(text: &str) -> usize {
text.split_whitespace().count()
}
fn sum(values: &[i32]) -> i32 {
values.iter().sum()
}
fn main() {
let s = String::from("one two three");
let v = vec![1, 2, 3];
println!("{}", count_words(&s));
println!("{}", count_words("literal text"));
println!("{}", sum(&v));
println!("{}", sum(&[4, 5]));
}The first call passes &String, the second passes &'static str, and both work with one signature. Elision gives each function the lifetime it needs, so nothing is annotated.
Use `&mut T` to change the caller's data
When the function updates data the caller owns, take &mut T. The caller needs a mut binding and writes &mut at the call site, which makes the mutation visible when reading the code.
An alternative is to take ownership and give it back:
fn shout(mut s: String) -> String {
s.push('!');
s
}
fn shout_in_place(s: &mut String) {
s.push('!');
}
fn main() {
let a = String::from("hey");
let a = shout(a);
let mut b = String::from("hey");
shout_in_place(&mut b);
println!("{a} {b}");
}Both work. The &mut version is usually clearer for plain updates, and the caller never has to rebind the variable. Taking and returning ownership suits transformations in a chain, such as builder-style methods that return Self.
Take ownership when the function keeps the value
Take T by value when the function stores the value, sends it to another thread, or consumes it. A struct constructor is the usual case. If User holds a String, the constructor needs to own one, because a borrowed &str would force User to carry a lifetime.
struct User {
name: String,
}
impl User {
fn new(name: String) -> User {
User { name }
}
}
fn main() {
let name = String::from("Ada");
let user = User::new(name);
println!("{}", user.name);
}After User::new(name), the variable name is moved. Using it again is error E0382:
struct User {
name: String,
}
impl User {
fn new(name: String) -> User {
User { name }
}
}
fn main() {
let name = String::from("Ada");
let user = User::new(name);
println!("{} {}", user.name, name);
}This does not compile: name was moved into User::new, so the final println! borrows a moved value.
The signature tells the caller the cost up front. A function that takes String says "give me a string you no longer need". If most callers have a &str, they must allocate before calling, and that allocation is the price of ownership.
Let the caller pass either kind
You can make the constructor friendlier with impl Into<String>. Callers pass a literal or an owned String and the conversion happens inside.
struct User {
name: String,
}
impl User {
fn new(name: impl Into<String>) -> User {
User { name: name.into() }
}
}
fn main() {
let a = User::new("Ada");
let owned = String::from("Grace");
let b = User::new(owned);
println!("{} {}", a.name, b.name);
}A &str allocates inside into(). A String moves in without copying. The caller chooses the cost.
The trade-off is that generic parameters create one compiled copy of the function per type, and they make the signature harder to read. Use this pattern for public constructors and setters. For ordinary helpers, plain &str or String is simpler.
Clone when you need an independent copy
.clone() makes a separate value, so both the original and the copy are usable. For String and Vec<T> this allocates and copies the contents.
struct User {
name: String,
}
impl User {
fn new(name: String) -> User {
User { name }
}
}
fn main() {
let name = String::from("Ada");
let user = User::new(name.clone());
println!("{} {}", user.name, name);
}Clone is the right tool when two parts of the program each need to own the data, for example a name used as a map key and also stored in a record. It is a poor tool when used only to silence the compiler.
Compare two ways to hold a value across a mutation:
fn main() {
let mut names = vec![String::from("a"), String::from("b")];
let first = names[0].clone();
names.push(String::from("c"));
println!("{first} {}", names.len());
}Here the clone ends the borrow of names immediately, which resolves an E0502 conflict, but it costs an allocation. Often you can reorder instead: read what you need, finish using the borrow, then mutate. Because of non-lexical lifetimes, the borrow ends at its last use. Try reordering first, and clone when the program genuinely needs two owners.
Cloning a Vec<String> copies every string, so a clone inside a loop can turn a cheap operation into a slow one. For shared ownership without copying the contents, Rc<T> or Arc<T> clones only a pointer and a counter. Those types are outside this chapter.
Copy types: just pass by value
Small types that implement Copy, such as integers, f64, bool, char, and tuples of those, are duplicated bit for bit on every use. Passing &i32 instead of i32 is rarely useful, because the reference is no smaller than the value and adds a dereference.
fn double(n: i32) -> i32 {
n * 2
}
fn main() {
let x = 21;
println!("{} {}", double(x), x);
}After the call x is still valid, since the call copied it. A rough rule: pass Copy types that are a few words or fewer by value, and borrow anything larger or anything that owns heap data.
Return types follow the same logic
A return type is also a choice between borrowing and owning.
- Return a borrow (
&str,&T) when the result is a view into an input. Elision ties its lifetime to the input. - Return an owned value (
String,Vec<T>) when the function builds something new. A reference to a local value would dangle.
fn longest_line(text: &str) -> &str {
text.lines().max_by_key(|l| l.len()).unwrap_or("")
}
fn to_upper(text: &str) -> String {
text.to_uppercase()
}
fn main() {
let doc = String::from("short\na much longer line\nmid");
let line = longest_line(&doc);
let loud = to_upper(line);
println!("{line} | {loud}");
}longest_line returns a slice of doc, so no allocation occurs, but line keeps doc borrowed. to_upper builds new text, so the result is owned and independent of its input.
Common mistakes
- Taking
Stringwhen you only read it. Every caller with a&strmust allocate, and callers with aStringlose it. Take&str. - Taking
&Stringor&Vec<T>. This narrows what callers can pass. Use&strand&[T]. - Taking
&mut Twhen&Tis enough. This blocks other readers while the call runs, and it makes the caller declaremut. - Cloning inside a hot loop to dodge a borrow error. Restructure the code so the borrow ends sooner, or borrow the data once outside the loop.
- Storing
&strin a struct to avoid allocating. This works, but the struct then needs a lifetime parameter and cannot outlive its source. If the struct must be returned or sent to another thread, useString.
Exercises
Exercise
A function fn register(name: String) pushes name into a Vec<String> owned by a global registry. A caller has a &str. What are the two ways to call it, and what does each cost? How would you change the signature so callers with either type avoid an extra clone?
Show answer
The caller can write register(s.to_string()) or register(String::from(s)). Both allocate and copy the text once. A caller who already owns a String can pass it with no copy, but loses the variable. Changing the signature to fn register(name: impl Into<String>) lets callers pass &str, which allocates inside into(), or String, which moves in with no copy. Each caller pays only what it has to.
Exercise
Which signature is best for a function that counts how many elements of a list are even, and why: fn count_even(v: Vec<i32>) -> usize, fn count_even(v: &Vec<i32>) -> usize, or fn count_even(v: &[i32]) -> usize?
Show answer
The slice version, &[i32]. It only reads, so it should borrow, which rules out taking the Vec by value because that would consume the caller's vector. Between the two borrows, &[i32] accepts a &Vec<i32>, an array reference, and a sub-slice, while &Vec<i32> accepts only a vector reference.
Exercise
You write let first = &names[0]; names.push(String::from("x")); println!("{first}"); and get E0502. Name two fixes and say when each is appropriate.
Show answer
One fix is to clone: let first = names[0].clone();. That gives an independent owned value and ends the borrow, which is appropriate when you really need the old value after the push. The other is to reorder so println!("{first}") comes before names.push(...). The shared borrow then ends at its last use, and no copy is needed. Prefer reordering when it keeps the program's behavior the same.