Sub topic 6
Accepting slices in function parameters
This chapter assumes you know ownership, basic borrowing with & and &mut, and how Vec<T> and arrays store elements. It also assumes you have seen the &[T] type and range syntax such as &v[1..3].
Why parameters should be slices
Suppose a function only reads a list of numbers. You could write it three ways:
fn sum(v: Vec<i32>)takes ownership, so the caller loses the vector.fn sum(v: &Vec<i32>)borrows, but accepts only aVec.fn sum(v: &[i32])borrows and accepts any contiguous run ofi32values.
The third form is the most general. The function needs to read elements, so it should ask for a view of elements and not for a particular container.
fn sum(values: &[i32]) -> i32 {
values.iter().sum()
}
fn main() {
let arr = [1, 2, 3];
let v = vec![4, 5, 6];
println!("{}", sum(&arr));
println!("{}", sum(&v));
println!("{}", sum(&v[1..]));
}This prints 6, 15, and 11. One function handles an array, a whole vector, and a part of a vector.
How the arguments convert
The compiler converts each argument to &[i32] using a coercion. A coercion is an automatic type change at a function call.
| Argument type | Coercion used |
|---|---|
| `&[i32; 3]` | Unsized coercion (array to slice) |
| `&Vec<i32>` | Deref coercion (`Vec<T>` implements `Deref<Target = [T]>`) |
| `&Box<[i32]>` | Deref coercion |
| `&[i32]` | None needed |
The same rule for strings
For text, the parameter type is &str, not &String. A &String coerces to &str through deref, and a string literal already has type &str.
fn first_word(s: &str) -> &str {
match s.find(' ') {
Some(i) => &s[..i],
None => s,
}
}
fn main() {
let text = String::from("hello world");
println!("{}", first_word(&text));
println!("{}", first_word("single"));
}The function returns a slice of its input, so it allocates nothing. The returned &str is tied to the input through lifetime elision. With one reference parameter, the compiler gives the output the same lifetime as the input.
Mutable parameters
Use &mut [T] when the function changes elements in place but does not add or remove them.
fn double_all(values: &mut [i32]) {
for x in values.iter_mut() {
*x *= 2;
}
}
fn main() {
let mut v = vec![1, 2, 3, 4];
double_all(&mut v[..2]);
println!("{:?}", v);
}This prints [2, 4, 3, 4]. Only the first two elements were passed, so only they changed. If the function must call push or remove, it needs &mut Vec<T>, because a slice cannot change its length.
Common errors
- Taking
&Vec<T>or&String. This compiles, but it rejects arrays, slices, and string literals. Clippy reports it asptr_arg. - Expecting coercion inside generics. Deref coercion applies when the parameter type is known. With
fn show<T: Debug>(x: T), passing&vmakesTequal&Vec<i32>, with no conversion. Write the parameter as&[T]to get the coercion. - Mismatched element types. A
&Vec<String>does not convert to&[&str]. The element types differ, and coercion changes only the outer pointer. Accept&[String], or take a generic&[S]whereS: AsRef<str>. - Holding the result across a mutation. The slice returned by
first_wordborrows the original string. Callingtext.clear()while that result is still in use is a borrow error. The next chapter covers this.
When to take ownership instead
A slice parameter is the wrong choice when the function stores the data in a struct, sends it to another thread, or returns it in a new form. In those cases, taking a Vec<T> or String avoids a hidden copy inside the function and shows the cost at the call site.
Exercise
You wrote fn longest_len(words: &Vec<String>) -> usize, and a caller wants to pass the first three entries of a vector. How should you change the signature, and why does the caller's code then work?
Show answer
Change it to fn longest_len(words: &[String]) -> usize. The caller can then pass &words[..3], which is already a &[String]. Callers holding a whole Vec<String> can still pass &words, because &Vec<String> coerces to &[String] by deref coercion.
Exercise
A function fn shout(s: &String) -> String is called as shout("hi"). Why does this fail to compile, and what is the fix?
Show answer
A string literal has type &str, and there is no coercion from &str to &String. Change the parameter to &str. Callers with a String can still pass &name, which coerces to &str.