Sub topic 12
Converting between slices and owned data
This chapter covers how to turn borrowed slices (&[T], &str) into owned values (Vec<T>, String, Box<[T]>, arrays) and how to go back. It assumes you know ownership and moves, shared and mutable borrowing, and the basic use of Vec<T>, String, and range slicing such as &v[1..3].
Why conversions matter
A slice is a borrowed view. It owns nothing, so it cannot outlive the data it points into. Sometimes that is too restrictive. You may want to store the data in a struct, send it to another thread, or return it from a function whose input is gone. For those cases you need an owned copy.
The reverse direction costs almost nothing. An owned collection can lend out a slice at any time, with no allocation and no copying.
| Direction | Cost | Typical tools |
|---|---|---|
| Owned to slice | Free (builds a pointer and a length) | `&v`, `&v[..]`, `as_slice`, `as_str` |
| Slice to owned | Allocates and copies or clones every element | `to_vec`, `to_owned`, `to_string`, `Vec::from`, `into` |
| `Vec<T>` to `Box<[T]>` | No copy, but may reallocate to shrink | `into_boxed_slice`, `into_vec` |
| Slice to array | Checks the length, then copies (or borrows) | `try_into`, `copy_from_slice` |
From a slice to an owned Vec
The [T] type has two methods for this, and Vec has matching From implementations. All of them require T: Clone, because each element must be duplicated.
fn main() {
let arr = [1, 2, 3, 4, 5];
let s: &[i32] = &arr[1..4];
let v1: Vec<i32> = s.to_vec();
let v2: Vec<i32> = s.to_owned();
let v3: Vec<i32> = Vec::from(s);
let v4: Vec<i32> = s.into();
println!("{:?} {:?} {:?} {:?}", v1, v2, v3, v4);
assert_eq!(v1, v4);
}All four lines do the same work. to_vec says plainly what happens. to_owned comes from the ToOwned trait, which is useful in generic code. Vec::from and into fit best when the target type is already known, for example a function argument or a struct field.
For element types that are expensive to clone, such as Vec<String>, to_vec clones every element and allocates a new buffer. The cost grows with the length. Prefer passing the slice along when the receiver does not need ownership.
From &str to String
The string versions follow the same pattern. A String is a Vec<u8> that is guaranteed to hold valid UTF-8, so copying a &str is a byte copy.
fn main() {
let s: &str = "hello";
let a = s.to_string();
let b = String::from(s);
let c = s.to_owned();
let d: String = s.into();
assert!(a == b && b == c && c == d);
println!("{}", a);
}These are equivalent in effect. Pick one and stay consistent within a codebase. to_string goes through the Display machinery in generic code, but the standard library specializes it for str, so it is not slower here.
From owned data to a slice
Going the other way is cheap and usually implicit. Writing &v where a &[T] is expected triggers deref coercion, because Vec<T> implements Deref<Target = [T]>. String derefs to str, and Box<[T]> derefs to [T]. Arrays do not deref. They convert to slices through unsized coercion, which the compiler applies automatically at the same places.
fn total(xs: &[i32]) -> i32 {
xs.iter().sum()
}
fn main() {
let v = vec![1, 2, 3];
let boxed: Box<[i32]> = vec![4, 5].into_boxed_slice();
let arr = [6, 7];
println!("{}", total(&v));
println!("{}", total(&boxed));
println!("{}", total(&arr));
println!("{}", total(v.as_slice()));
println!("{}", total(&v[1..]));
}The explicit forms (as_slice, as_mut_slice, as_str, &v[..]) matter when coercion cannot happen. Typical cases are a generic parameter without a concrete target type, and a method chain where you want to select a method of [T] rather than one of Vec<T>.
Box<[T]> and Box<str>: owned, but fixed in size
A Vec<T> stores a pointer, a length, and a capacity. A Box<[T]> stores only a pointer and a length. It owns its elements but cannot grow. This saves one word per value and states in the type that the size will not change.
fn main() {
let mut v = Vec::with_capacity(100);
v.extend([1, 2, 3]);
let boxed: Box<[i32]> = v.into_boxed_slice(); // drops the spare capacity
println!("{} {:?}", boxed.len(), boxed);
let copy: Box<[i32]> = Box::from(&[7, 8, 9][..]);
println!("{:?}", copy);
let back: Vec<i32> = boxed.into_vec(); // no copy
println!("{:?}", back);
let name: Box<str> = String::from("ferris").into_boxed_str();
let name_back: String = name.into_string();
println!("{}", name_back);
}into_boxed_slice may reallocate if the capacity is larger than the length, so it is not always free. into_vec and into_string never copy.
From a slice to a fixed-size array
Converting a slice to [T; N] can fail, because the slice length is only known at run time. The conversion uses TryFrom, and it returns Err(TryFromSliceError) when the length differs from N. Copying into an owned array requires T: Copy. Borrowing as &[T; N] has no such requirement.
fn main() {
let v = vec![1u8, 2, 3, 4];
let s: &[u8] = &v;
let head: [u8; 2] = s[..2].try_into().unwrap(); // copies two bytes
let whole: &[u8; 4] = s.try_into().unwrap(); // borrows, no copy
let wrong: Result<[u8; 3], _> = s.try_into(); // length is 4, not 3
println!("{:?} {:?} {}", head, whole, wrong.is_err());
let n = u32::from_le_bytes(s.try_into().unwrap());
println!("{}", n);
}The last line shows the most common use of this conversion: parsing fixed-width integers out of a byte buffer. from_le_bytes takes [u8; 4], so the slice must have exactly four bytes. This code works without an import on the 2021 edition and later. On earlier editions you need use std::convert::TryInto;.
Copying into an existing buffer
If the destination already exists, you do not need a new allocation. Use copy_from_slice for Copy types and clone_from_slice for the rest.
fn main() {
let mut buf = [0u8; 6];
buf[..3].copy_from_slice(&[1, 2, 3]);
buf[3..].clone_from_slice(&[9, 8, 7]);
println!("{:?}", buf);
}Bytes and text
A &[u8] and a &str hold the same kind of data, but a str must be valid UTF-8. Converting from bytes to text is therefore checked. Converting from text to bytes never fails.
fn main() {
let bytes: Vec<u8> = vec![104, 105];
// Borrow: validates, then reuses the same memory.
let text: &str = std::str::from_utf8(&bytes).unwrap();
println!("{}", text);
// Lossy: invalid bytes become U+FFFD.
let lossy = String::from_utf8_lossy(&[0x68, 0xff, 0x69]);
println!("{}", lossy);
// Take ownership: validates, then reuses the Vec's buffer.
let owned: String = String::from_utf8(bytes).unwrap();
println!("{}", owned);
// Text to bytes never fails.
let raw: &[u8] = owned.as_bytes();
println!("{:?}", raw);
}String::from_utf8 consumes the Vec<u8> and does not copy it, so the validation pass is the only cost. If the bytes are invalid, the error returns the original vector through into_bytes. from_utf8_lossy returns a Cow<str>. It borrows when the input is already valid and allocates only when it has to replace bytes.
Choosing what to accept and what to return
The conversions above lead to a few rules for function signatures.
- Accept borrowed types for read-only work:
&[T]instead of&Vec<T>, and&strinstead of&String. Callers can then pass aVec, an array, aBox<[T]>, or a sub-range. - Accept an owned type only when the function must keep the data. A function that stores its input in a struct should take
Vec<T>orStringby value. That makes the caller decide where the allocation happens, and it avoids a hidden clone. - Return an owned type when the result is built inside the function. A function cannot return a slice of one of its own local
Vecs, because theVecis dropped when the function returns. Return theVec, or take an input slice and return a sub-slice of it with the same lifetime. - Use
impl Into<String>orimpl AsRef<[T]>only when you want to accept many input types and the extra generic code is worth it. A plain&stris simpler for most APIs.
struct Packet {
payload: Vec<u8>,
}
impl Packet {
// Copies once, inside the constructor, and the cost is visible to the caller.
fn from_slice(data: &[u8]) -> Packet {
Packet { payload: data.to_vec() }
}
// Takes ownership: no copy at all if the caller already has a Vec.
fn from_vec(data: Vec<u8>) -> Packet {
Packet { payload: data }
}
// Borrowed view of the owned data.
fn bytes(&self) -> &[u8] {
&self.payload
}
}
fn main() {
let buf = [1u8, 2, 3, 4];
let p1 = Packet::from_slice(&buf[1..]);
let p2 = Packet::from_vec(vec![9, 9]);
println!("{:?} {:?}", p1.bytes(), p2.bytes());
}Common mistakes
- Cloning in a loop. Calling
to_vec()orto_string()on every iteration to satisfy the borrow checker usually means the data should be borrowed for longer or restructured. Clone once, outside the loop, if you need ownership. - Taking
&Vec<T>or&Stringas parameters. These force callers to hold aVecorString. Clippy flags them withptr_arg. - Expecting
try_intoto truncate. Converting a six-element slice into[T; 4]returns an error. It does not take the first four elements. Slice to the exact range first. - Using
unwraponfrom_utf8for outside input. Network and file data may be invalid UTF-8. Handle theErr, or usefrom_utf8_lossywhen replacement characters are acceptable. - Forgetting that
to_vecneedsClone. For a type that is notClone, you cannot copy from a slice. Either move the elements out of an ownedVecor implementClone.
Exercise
A function fn parse_header(data: &[u8]) -> Option<u16> should read the first two bytes of data as a big-endian u16. It returns None if data has fewer than two bytes. Write the function body using a conversion from this chapter.
Show answer
Slice to exactly two bytes with get, then convert to an array.
fn parseheader(data: &[u8]) -> Option<u16> {
let head: [u8; 2] = data.get(..2)?.tryinto().ok()?;
Some(u16::frombebytes(head))
}
data.get(..2) returns None for short input instead of panicking. try_into() turns the &[u8] of length 2 into [u8; 2], and ok() converts the infallible-in-practice error into an Option. from_be_bytes builds the integer.
Exercise
What is the difference in cost between let a: &[i32] = &v; and let b: Vec<i32> = a.to_vec();, where v is a Vec<i32> of one million elements? Name the reason b can outlive v while a cannot.
Show answer
Creating a copies only a pointer and a length (two words), so it costs the same for any size. Creating b allocates a new buffer and copies one million i32 values, so the cost grows with the length. a is a borrow of v's buffer, so the borrow checker requires v to stay alive while a is used. b owns its own buffer and does not depend on v.
Exercise
Why does String::from_utf8(bytes) take a Vec<u8> by value, while std::str::from_utf8(&bytes) takes a borrowed slice?
Show answer
String::from_utf8 produces an owned String that reuses the vector's heap buffer after validating it, so it must consume the Vec<u8>. str::from_utf8 produces a &str that points into the existing bytes, so it only needs to borrow them, and the result is valid only as long as the borrow.