Sub topic 6
Accepting slices in function parameters
This chapter assumes you know ownership and moves, shared and mutable references, and the basics of Vec<T> and arrays. You have already seen that &a[1..4] produces a &[i32]. Here you will use that type to design function signatures that accept many kinds of callers.
Why parameters should be slices
Suppose you write a function that sums integers. The first signature that comes to mind might be one of these:
fn sum(values: Vec<i32>) -> i32takes ownership. The caller loses its vector, or must clone it.fn sum(values: &Vec<i32>) -> i32borrows, but only accepts aVec. Arrays and sub-ranges are rejected.fn sum(values: &[i32]) -> i32borrows a view of any contiguous run ofi32values.
The third form is almost always the right choice. A function that only reads elements needs a pointer and a length, and a slice supplies exactly that. Asking for a &Vec<i32> also demands the vector's capacity field and implies that the data lives on the heap, and the function uses neither.
The same rule applies to text. Prefer &str to &String, and &Path to &PathBuf.
fn sum(values: &[i32]) -> i32 {
values.iter().sum()
}
fn main() {
let arr = [1, 2, 3];
let v = vec![4, 5, 6, 7];
println!("{}", sum(&arr));
println!("{}", sum(&v));
println!("{}", sum(&v[1..3]));
println!("{}", sum(&[]));
}This prints 6, 22, 11, and 0. One function serves an array, a whole vector, part of a vector, and an empty slice.
What converts to a slice
Three different conversions make the calls above compile. They all happen automatically at a coercion site, which includes function arguments, let statements with an explicit type, and struct fields.
| Argument you pass | Parameter type | Mechanism |
|---|---|---|
| `&Vec<T>` | `&[T]` | Deref coercion (`Vec<T>` implements `Deref<Target = [T]>`) |
| `&[T; N]` | `&[T]` | Unsized coercion (the compiler attaches length `N`) |
| `&String` | `&str` | Deref coercion (`String` implements `Deref<Target = str>`) |
| `&Box<[T]>` | `&[T]` | Deref coercion |
| `&mut Vec<T>` | `&mut [T]` | Deref coercion through `DerefMut` |
| `&mut [T; N]` | `&mut [T]` | Unsized coercion |
Deref coercion can chain. A &Box<Vec<i32>> becomes &Vec<i32> and then &[i32], because the compiler keeps applying Deref until the types match or it runs out of options.
Strings follow the same pattern
The first_word function from the topic's examples shows the idea for &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"));
}Here &text is a &String, which deref-coerces to &str. The literal "single" already has type &'static str. Had the parameter been &String, the literal call would not compile, because a literal is not a String. Callers would be forced to write &"single".to_string() and allocate for nothing.
Returning slices and lifetimes
When a function has exactly one reference parameter, the compiler ties the returned reference to it. first_word relies on this rule, called lifetime elision. The returned &str borrows from s, so it cannot outlive the caller's String.
This has a practical consequence. If you call first_word(&text), keep the result, and then call text.clear(), the compiler rejects the program. clear needs a mutable borrow while the returned slice still holds a shared one. Chapter 7 covers this in detail. For now, remember that a slice you return is a live borrow of the argument you passed in.
With two or more reference parameters, elision cannot choose, so you must name the lifetime:
fn longer<'a>(a: &'a [i32], b: &'a [i32]) -> &'a [i32] {
if a.len() >= b.len() { a } else { b }
}
fn main() {
let x = [1, 2, 3];
let y = vec![9, 8];
println!("{:?}", longer(&x, &y));
println!("{:?}", longer(&y, &x[..1]));
}The output is [1, 2, 3] and then [9, 8]. The annotation 'a says the result is valid only as long as both inputs are.
Generic element types
Slices combine naturally with generics. The slice stays in the signature, and only the element type varies:
fn largest<T: PartialOrd>(items: &[T]) -> Option<&T> {
let mut iter = items.iter();
let mut best = iter.next()?;
for item in iter {
if item > best {
best = item;
}
}
Some(best)
}
fn main() {
println!("{:?}", largest(&[3, 9, 2]));
let words = vec!["pear", "apple"];
println!("{:?}", largest(&words));
println!("{:?}", largest::<i32>(&[]));
}This prints Some(9), Some("pear"), and None. Returning Option<&T> handles the empty slice without a panic. It also returns a reference into the caller's data, so no element is cloned or moved.
Mutable slice parameters
A &mut [T] parameter lets a function change elements in place. It cannot change the length.
fn zero_negatives(values: &mut [i32]) {
for v in values.iter_mut() {
if *v < 0 {
*v = 0;
}
}
}
fn main() {
let mut v = vec![3, -1, 4, -1, 5];
zero_negatives(&mut v);
println!("{:?}", v);
let mut a = [-2, 7, -9];
zero_negatives(&mut a);
println!("{:?}", a);
let mut w = vec![-1, -2, -3, -4];
zero_negatives(&mut w[..2]);
println!("{:?}", w);
}The output is [3, 0, 4, 0, 5], [0, 7, 0], and [0, 0, -3, -4]. The last call touches only the first two elements. The function cannot see or alter the rest.
The inability to resize is a strength, not just a limit. A function with a &mut [T] parameter promises not to reallocate, so no other pointer into the buffer can be invalidated by the call.
When a slice is the wrong parameter
A slice cannot do everything. Use the table to pick a parameter type.
| You need to | Parameter type |
|---|---|
| Read elements | `&[T]` |
| Change elements, not the length | `&mut [T]` |
| Add or remove elements | `&mut Vec<T>` |
| Keep the data after the call, or move it elsewhere | `Vec<T>` (owned) |
| Return a modified copy | `&[T]` in, `Vec<T>` out |
Two small functions show the last two rows:
fn sorted_copy(values: &[i32]) -> Vec<i32> {
let mut out = values.to_vec();
out.sort();
out
}
fn append_squares(out: &mut Vec<i32>, input: &[i32]) {
out.extend(input.iter().map(|x| x * x));
}
fn main() {
let original = [5, 1, 4];
println!("{:?}", sorted_copy(&original));
println!("{:?}", original);
let mut results = vec![0];
append_squares(&mut results, &original);
println!("{:?}", results);
}This prints [1, 4, 5], then [5, 1, 4] (the original is untouched), then [0, 25, 1, 16]. The function that grows a vector asks for &mut Vec<i32> because pushing is a Vec operation. Its input is still a plain slice.
Going more general with AsRef
A &[T] parameter forces callers to write &. When you want to accept owned values as well as borrowed ones, AsRef widens the signature:
fn total(values: impl AsRef<[i32]>) -> i32 {
values.as_ref().iter().sum()
}
fn count_words(text: impl AsRef<str>) -> usize {
text.as_ref().split_whitespace().count()
}
fn main() {
println!("{}", total(vec![1, 2, 3]));
println!("{}", total([4, 5]));
println!("{}", total(&[6, 7]));
println!("{}", count_words("a b c"));
println!("{}", count_words(String::from("x y")));
println!("{}", count_words(&String::from("p q r s")));
}The output is 6, 9, 13, 3, 2, 4. Every call compiles without an explicit & or conversion.
This flexibility has costs:
- Each distinct argument type produces its own compiled copy of the function (monomorphization). A plain
&[i32]produces one. - Error messages get harder to read when the trait bound is not met.
- Deref coercion does not apply to generic parameters, because the compiler has no concrete target type to coerce toward. This is why
AsRefexists as a separate mechanism.
For most code, plain &[T] is the better default. Reach for AsRef in public library APIs where the extra convenience matters, such as functions that take file paths.
Common mistakes
- Writing
&Vec<T>or&Stringin a signature. Callers holding arrays, slices, or literals must convert first. Change the type to&[T]or&str. - Expecting
&mut [T]to push. Slices have nopush. If the function must grow the buffer, take&mut Vec<T>. - Forgetting lifetimes with two reference parameters. The compiler reports a missing lifetime specifier. Add
'ato the inputs that the result may borrow from. - Holding a returned slice across a mutation. The result of
first_word(&s)keepssborrowed. Convert it with.to_string()or.to_vec()if you need to mutate the source afterward. - Assuming the slice is non-empty.
values[0]panics on an empty slice. Usevalues.first()orvalues.get(0), which returnOption.
Exercise
A colleague wrote fn average(nums: &Vec<f64>) -> f64. Rewrite the signature so that it accepts an array, a Vec, and a sub-range such as &v[2..]. Then write the body so that an empty input returns None instead of dividing by zero. What is the full signature, and what does average(&[]) return?
Show answer
Use fn average(nums: &[f64]) -> Option<f64>. The body is if nums.is_empty() { None } else { Some(nums.iter().sum::<f64>() / nums.len() as f64) }. The call average(&[]) returns None. Using &[f64] lets callers pass &array, &vec, and &vec[2..] through coercion.
Exercise
You write fn push_default(items: &mut [i32]) { items.push(0); }. It does not compile. Why, and what is the smallest change to the signature that fixes it? What does the fix cost the caller?
Show answer
A slice has a fixed length and no push method, since it is only a view into storage it does not own. Changing the parameter to &mut Vec<i32> fixes it. The cost is that callers can no longer pass arrays or sub-slices. They must hold a Vec<i32>.