Sub topic 12
Converting between slices and owned data
This chapter assumes you know how &[T] and &str borrow data, how Vec<T> and String own it, and how deref coercion lets &Vec<T> stand in for &[T]. Here you will move data in both directions: from a borrowed view to an owned value, and back.
Why conversion costs differ
Going from owned to borrowed is free. You are only creating a pointer and a length. Going from borrowed to owned allocates memory and copies the elements, because the slice does not own what it points at.
The last two arrows between Vec<T> and Box<[T]> move ownership of the same allocation. They do not copy elements.
From a slice to owned data
Use to_vec for a Vec<T>. Vec::from and .into() do the same job. All of them require T: Clone, because each element must be duplicated.
fn main() {
let a = [1, 2, 3, 4, 5];
let s: &[i32] = &a[1..4];
let v1: Vec<i32> = s.to_vec();
let v2: Vec<i32> = s.into();
let b: Box<[i32]> = s.into();
let name: &str = "slice";
let owned: String = name.to_owned();
let boxed: Box<str> = name.into();
println!("{:?} {:?} {:?}", v1, v2, b);
println!("{} {}", owned, boxed);
}For strings, to_string, to_owned, String::from, and .into() all produce a String from a &str. Pick one and use it consistently. to_owned states the intent most directly.
If the element type is not Clone, to_vec will not compile. You then need to keep ownership of the original, or build the new collection some other way.
From owned data to a slice
Borrowing is usually implicit, thanks to deref coercion. When you need to be explicit, for example in a method chain or when inference is unclear, use as_slice or &v[..].
fn total(xs: &[i32]) -> i32 {
xs.iter().sum()
}
fn main() {
let v = vec![1, 2, 3];
let boxed: Box<[i32]> = v.into_boxed_slice();
println!("{}", total(&boxed));
let back: Vec<i32> = boxed.into_vec();
println!("{}", total(back.as_slice()));
}Box<[T]> is an owned slice with no spare capacity. It is a little smaller than a Vec<T>, since it stores a pointer and length but no capacity. It is useful for data you will not grow. into_boxed_slice may reallocate to drop unused capacity. into_vec never copies.
From a slice to a fixed-size array
A slice has its length known only at run time, while an array's length is part of its type. Converting therefore can fail, so it returns a Result.
use std::convert::TryFrom;
fn main() {
let v = vec![10, 20, 30, 40];
let head: [i32; 2] = <[i32; 2]>::try_from(&v[..2]).unwrap();
let wrong = <[i32; 3]>::try_from(&v[..2]);
println!("{:?} {}", head, wrong.is_err());
}This prints [10, 20] true. The use line is only required before the 2021 edition. This conversion copies elements, so T must be Copy. If you only need a borrowed fixed-size view, <&[i32; 2]>::try_from(&v[..2]) gives a reference to an array and copies nothing.
Summary of conversions
| From | To | Method | Cost |
|---|---|---|---|
| `&[T]` | `Vec<T>` | `to_vec`, `into` | Allocate and clone |
| `&[T]` | `Box<[T]>` | `Box::from`, `into` | Allocate and clone |
| `&str` | `String` | `to_owned`, `to_string` | Allocate and copy |
| `Vec<T>` | `&[T]` | `&v`, `as_slice` | Free |
| `Vec<T>` | `Box<[T]>` | `into_boxed_slice` | May reallocate |
| `Box<[T]>` | `Vec<T>` | `into_vec` | Free |
| `&[T]` | `[T; N]` | `try_from` | Copy, can fail |
Common errors
- Returning a slice of a local. A function that builds a
Vecand returns&v[..]fails with a "does not live long enough" error. Return theVecitself, or returnv.into_boxed_slice(). - Cloning too early. Calling
to_vecjust to pass data to a function that takes&[T]wastes an allocation. Pass&vinstead. - Cloning too late. If a struct must outlive the buffer it was parsed from, store
StringorVec<T>rather than a borrowed slice. Convert once at the boundary. - Expecting
try_fromto truncate. A length mismatch is an error, not a partial copy.
Exercise
A function receives data: &[u8] and must store the first four bytes in a struct field of type [u8; 4]. Which expression does this, and what happens if data has only three bytes?
Show answer
Use <[u8; 4]>::try_from(&data[..4]). Note that &data[..4] panics with three bytes, because the range is out of bounds. To avoid the panic, call data.get(..4) first, then convert the Some value with try_from. Since data.get(..4) returns None for short input, the function can then report an error without panicking.