Sub topic 4
Borrow instead of clone: &str, &[T] and references in APIs
This chapter assumes you know ownership, borrowing and basic lifetimes, and that you can use Vec, String and cargo test. The previous chapter showed that clone and to_string hide allocations. Here you will remove many of them by choosing better function signatures.
The working model
A String owns a heap buffer. A &str is only a pointer and a length into some existing text, so creating one never allocates. &[T] relates to Vec<T> the same way. When a function only reads its input, a borrowed parameter lets the caller pass data without copying it.
Owned parameters force clones
fn count_vowels_owned(s: String) -> usize {
s.chars().filter(|c| "aeiou".contains(*c)).count()
}
fn count_vowels(s: &str) -> usize {
s.chars().filter(|c| "aeiou".contains(*c)).count()
}
fn main() {
let name = String::from("Ferrous oxide");
let a = count_vowels_owned(name.clone()); // allocates a copy
let b = count_vowels(&name); // no allocation
let c = count_vowels("a string literal"); // no allocation
println!("{} {} {} {}", a, b, c, name);
}The first call needs name.clone() because the function consumes its argument and name is used again later. The &str version accepts a &String through deref coercion, and it also accepts string literals and slices of larger strings.
Slices work the same way
fn sum(xs: &[u32]) -> u32 {
xs.iter().sum()
}
fn main() {
let v = vec![1, 2, 3, 4];
let arr = [10, 20, 30];
println!("{} {} {}", sum(&v), sum(&arr), sum(&v[1..3]));
}One &[u32] parameter serves a Vec, an array and a sub-range, and none of the calls copy elements.
Return borrowed data
A function can return a slice of its input instead of building a new String.
fn first_word(s: &str) -> &str {
s.split_whitespace().next().unwrap_or("")
}
fn main() {
let line = String::from("hello brave new world");
let w = first_word(&line);
println!("{}", w);
}Lifetime elision ties the returned reference to the input. The result is valid only while line is alive and unchanged.
Choosing a parameter type
| The function... | Take |
|---|---|
| reads text | `&str` |
| reads a sequence | `&[T]` |
| modifies in place | `&mut String` or `&mut Vec<T>` |
| stores the value | `String` or `Vec<T>` (owned) |
| may or may not store it | `impl Into<String>` or `Cow` (next chapter) |
Common errors
- Taking
&Stringor&Vec<T>. These are strictly less flexible than&strand&[T]. Clippy flags them withptr_arg. - Cloning to silence the borrow checker. If the compiler complains, first check whether a shorter borrow, a reordered statement or a smaller scope fixes it. A clone that "fixes" an error usually adds an allocation without making the design better.
- Borrowing what you need to keep. If a struct must outlive its source,
&'a strfields will not compile. Store aStringthere. Borrowing is worth it when the data lives long enough. - Returning a reference to a local.
fn f() -> &strthat points at aStringcreated insidefcannot compile. Return theString, or take the buffer as a parameter.
Borrowed structs
A short-lived struct can borrow from its input, such as a parsed line that is dropped before the buffer.
struct Pair<'a> {
key: &'a str,
value: &'a str,
}
fn parse(line: &str) -> Option<Pair<'_>> {
let (key, value) = line.split_once('=')?;
Some(Pair { key: key.trim(), value: value.trim() })
}
fn main() {
let line = String::from("mode = fast");
if let Some(p) = parse(&line) {
println!("{} -> {}", p.key, p.value);
}
}Parsing allocates nothing, because both fields point into line.
Exercise
A function fn tag(items: &Vec<String>) -> usize only counts items that start with "x". Which signature change removes the restriction on callers, and does it save an allocation?
Show answer
Change it to fn tag(items: &[String]) -> usize. Callers can then pass a Vec, an array or a sub-slice. It saves no allocation by itself, but it removes the need for callers to build a Vec just to call the function. Taking &[&str] would go further if callers hold string slices.