Sub topic 4
Borrow instead of clone: &str, &[T] and references in APIs
This chapter assumes you know ownership, borrowing and lifetime elision, and that you can read a function signature with &, &mut and a named lifetime. Earlier chapters showed how to count allocations and spot clone, to_string and collect. This chapter fixes the most common source of those allocations: function signatures that demand owned data when they only need to read it.
Why the signature decides the allocation
A function signature sets a rule for every caller. If a function takes String, each caller must produce an owned String. A caller that holds a &str has to allocate one first, and that allocation happens even if the function only reads the text.
fn is_valid_owned(name: String) -> bool {
!name.is_empty() && name.chars().all(|c| c.is_alphanumeric())
}
fn is_valid(name: &str) -> bool {
!name.is_empty() && name.chars().all(|c| c.is_alphanumeric())
}
fn main() {
let input = String::from("ada42");
// Allocates a second String only to read it.
println!("{}", is_valid_owned(input.clone()));
// Allocates nothing.
println!("{}", is_valid(&input));
}Both functions have the same body. The only difference is the cost placed on the caller. In library code you do not control the callers, so a borrowed parameter is almost always the better default.
Choose the borrowed form of each owned type
Each common owning type has a borrowed counterpart that works as a read-only parameter.
| Owned type | Borrowed parameter | What it accepts |
|---|---|---|
| `String` | `&str` | `String`, string literals, `Box<str>`, `Rc<str>`, substrings |
| `Vec<T>` | `&[T]` | `Vec<T>`, arrays, slices of either |
| `PathBuf` | `&Path` | `PathBuf`, `String`, `&str` (via `AsRef<Path>`) |
| `Box<T>` | `&T` | `Box<T>`, values on the stack, fields of structs |
| `Option<String>` | `Option<&str>` | Call `opt.as_deref()` to convert without cloning |
The borrowed form is also more general. &str accepts every string source, and &[T] accepts every contiguous sequence.
fn count_vowels(text: &str) -> usize {
text.chars().filter(|c| "aeiouAEIOU".contains(*c)).count()
}
fn mean(values: &[f64]) -> Option<f64> {
if values.is_empty() {
return None;
}
Some(values.iter().sum::<f64>() / values.len() as f64)
}
fn main() {
let owned = String::from("Borrowing is cheap");
let boxed: Box<str> = "boxed text".into();
println!("{}", count_vowels(&owned));
println!("{}", count_vowels("a literal"));
println!("{}", count_vowels(&boxed));
let v = vec![1.0, 2.0, 3.0];
let arr = [4.0, 5.0];
println!("{:?} {:?} {:?}", mean(&v), mean(&arr), mean(&v[1..]));
}The calls with &owned, &boxed and &v compile because of deref coercion. The compiler converts &String to &str, &Box<str> to &str and &Vec<T> to &[T] at the call site, at no runtime cost.
Do not write `&String` or `&Vec<T>`
A parameter of type &String can only be called with a String. A parameter of type &Vec<T> can only be called with a Vec. Both are narrower than the slice forms and give you nothing extra, since you can't push to a shared reference. Clippy flags this with the ptr_arg lint. Use &str and &[T] instead.
Return borrowed data when the input outlives the result
Return values cause the same problem. A function that returns String or Vec<String> allocates for every piece of the result, even when each piece is a window into the input.
struct Record<'a> {
name: &'a str,
city: &'a str,
}
fn parse_record(line: &str) -> Option<Record<'_>> {
let mut parts = line.split(',');
let name = parts.next()?.trim();
let city = parts.next()?.trim();
Some(Record { name, city })
}
fn longest(words: &[String]) -> Option<&str> {
words.iter().map(|w| w.as_str()).max_by_key(|w| w.len())
}
fn main() {
let line = String::from("Ada, London");
if let Some(r) = parse_record(&line) {
println!("{} lives in {}", r.name, r.city);
}
let words = vec!["tea".to_string(), "coffee".to_string()];
println!("{:?}", longest(&words));
}parse_record makes no allocations. split, next and trim all return subslices of line. The '_ lifetime tells the compiler that a Record borrows from the argument. With a single input reference, lifetime elision handles the rest, so the signature stays short.
The price is that Record cannot outlive line. The next section covers when that price is too high.
When ownership is the right choice
Borrowing is not always correct. Use an owned parameter when the function keeps the data.
struct User {
name: String,
}
impl User {
fn new(name: impl Into<String>) -> Self {
Self { name: name.into() }
}
}
fn main() {
let a = User::new("ada"); // one allocation, inside into()
let existing = String::from("grace");
let b = User::new(existing); // moved in, no new allocation
println!("{} {}", a.name, b.name);
}If new took &str, it would have to call to_string internally, and a caller who already held a String would pay for a second allocation. With impl Into<String>, a caller with a String moves it in, and a caller with a &str pays exactly one allocation. Use the same idea for Vec<T> parameters that get stored.
Keep three rules in mind:
- Take
&stror&[T]when the function only reads. - Take an owned value or
impl Into<...>when the function stores the value in a struct, collection or returned value. - Return owned data when the result must outlive the input, such as data sent to another thread or kept in a cache.
impl AsRef<str> is a third option for read-only parameters. It accepts String, &str and more without a coercion. It is generic, so the compiler generates one copy of the function per argument type, which increases compile time and binary size. For a plain &str parameter, the generic version buys you nothing.
Clones that exist only to calm the borrow checker
A frequent source of avoidable allocations is a clone added to silence a borrow error. Before cloning, check whether the clone can be replaced by a shorter borrow, a reorder of statements, or a reference.
fn main() {
let names = vec!["ada".to_string(), "grace".to_string(), "alan".to_string()];
let mut lengths = Vec::with_capacity(names.len());
// Cloning each name just to read its length.
for name in names.clone() {
lengths.push(name.len());
}
// Borrowing is enough.
let mut lengths2 = Vec::with_capacity(names.len());
for name in &names {
lengths2.push(name.len());
}
println!("{:?} {:?}", lengths, lengths2);
}The first loop allocates once for the outer Vec and once per name. The second loop allocates nothing beyond the result vector. Clippy's redundant_clone and needless_pass_by_value lints catch some of these cases, but not all, so review .clone() calls by hand during an allocation audit.
Looking up in maps without building a key
A map keyed by String can be queried with a &str, because String implements Borrow<str>. This avoids building an owned key for lookups.
use std::collections::HashMap;
fn main() {
let mut counts: HashMap<String, u32> = HashMap::new();
for word in "a b a c b a".split_whitespace() {
if let Some(c) = counts.get_mut(word) {
*c += 1;
} else {
counts.insert(word.to_string(), 1);
}
}
let mut pairs: Vec<_> = counts.iter().collect();
pairs.sort();
println!("{:?}", pairs);
}This code allocates a key only the first time it sees a word. The common alternative, counts.entry(word.to_string()), allocates a String on every iteration, including when the key already exists. The entry API takes an owned key, so on stable Rust you trade a second hash lookup for fewer allocations. Measure with the counting allocator before choosing, because the lookup cost depends on key size and map size.
Common errors
- Returning a reference to a local variable fails with "cannot return reference to local variable". The data is dropped when the function ends. Return an owned value, or take the buffer as a parameter and return a slice of it.
- Mixing up two input lifetimes causes an "explicit lifetime required" error when the function has more than one reference parameter and returns a reference. Name the lifetime that the result borrows from, as in
fn pick<'a>(a: &'a str, _b: &str) -> &'a str. - Converting back with
to_owned()inside a helper hides the allocation behind a clean signature. If a function takes&strand immediately callsto_string, it should probably take an owned value. - Over-borrowing in async code or threads can fail, because spawned tasks usually need
'staticdata. Moving an owned value in is the correct choice there, not a failure of the technique.
Exercise
A function fn tag(label: &str) -> Tag builds Tag { label: label.to_string() }. Most callers already hold a String named label and call tag(&label), then drop label. Count the allocations per call and rewrite the signature so those callers allocate nothing extra, while callers with a &str still work.
Show answer
Each call allocates once, in to_string, and the caller's original String is then dropped, so the work is wasted. Change the signature to fn tag(label: impl Into<String>) -> Tag and build Tag { label: label.into() }. A caller with a String moves it in with no new allocation. A caller with a &str still allocates exactly once, which is unavoidable because Tag owns its text.
Exercise
You write fn first_two(items: &Vec<String>) -> Vec<String> that returns the first two elements cloned. Rewrite the signature and body so that it allocates nothing, and state the condition callers must meet.
Show answer
Use fn first_two(items: &[String]) -> &[String] { &items[..items.len().min(2)] }. The result is a borrowed slice of the input, so no allocation happens. Callers must keep items alive and unmodified for as long as they use the returned slice. If they need data that outlives items, they clone at that point.