Sub topic 2
What a slice is
This chapter assumes you know basic Rust syntax, ownership and moves, shared and mutable references, and the difference between arrays and Vec<T>. It defines the slice type, shows how a slice relates to the storage behind it, and covers the properties you need before the later chapters on ranges, bounds checking, and borrowing.
A view into contiguous data
A slice is a reference to a run of consecutive elements of the same type. It does not own those elements and does not copy them. It records where the run starts and how many elements it contains.
The type is written [T], and you almost always meet it behind a reference: &[T] for read-only access and &mut [T] for read-write access. [T] by itself means "some number of T values in a row, count unknown at compile time."
fn main() {
let a = [10, 20, 30, 40, 50];
let s = &a[1..4];
println!("{:?} len={}", s, s.len());
}This prints [20, 30, 40] len=3. The expression &a[1..4] borrows elements 1, 2 and 3 of the array. Its type is &[i32]. The array a still owns the data, and s only looks at part of it.
Array, Vec, and slice compared
All three describe consecutive elements in memory. They differ in who owns the elements and when the length is known.
| Type | Owns its elements | Length known | Where the elements live |
|---|---|---|---|
| `[T; N]` | Yes | At compile time, part of the type | Wherever the array value is (often the stack) |
| `Vec<T>` | Yes | At run time, can change | Heap buffer |
| `[T]` behind `&` or `&mut` | No, it borrows | At run time, fixed for that reference | Inside some array, `Vec`, or other owner |
The array's length is part of its type, so [i32; 3] and [i32; 4] are different types. A slice's length is not part of its type, so one function signature can accept views of any length.
Slices of the whole collection
A slice does not have to be a sub-range. A reference to a whole array or Vec can be used as a slice of all its elements.
fn total(values: &[i32]) -> i32 {
values.iter().sum()
}
fn main() {
let array = [1, 2, 3];
let vector = vec![4, 5, 6, 7];
println!("{}", total(&array));
println!("{}", total(&vector));
println!("{}", total(&vector[1..3]));
}The output is 6, 22, and 11. Three different sources reach the same function:
&arrayhas type&[i32; 3]. Rust converts it to&[i32]automatically. This is called unsized coercion, because the array's compile-time length is dropped.&vectorhas type&Vec<i32>. Rust converts it to&[i32]through deref coercion, becauseVec<T>implementsDeref<Target = [T]>.&vector[1..3]already has type&[i32].
Because of this, a parameter of type &[T] is usually better than &Vec<T> or &[T; N]. The later chapter on function parameters covers this in detail.
What a slice looks like in memory
A &[T] value holds two machine words: a pointer to the first element and a count of elements. Nothing else is stored. The elements stay where they were.
You can observe the two-word size directly. The numbers below are for a 64-bit target.
use std::mem::{size_of, size_of_val};
fn main() {
let a = [1i32, 2, 3, 4, 5];
let s: &[i32] = &a;
println!("{}", size_of::<&i32>());
println!("{}", size_of::<&[i32]>());
println!("{}", size_of_val(s));
}This prints 8, 16, and 20. A plain reference to one i32 is one pointer, 8 bytes. A slice reference is a pointer plus a length, 16 bytes. size_of_val(s) reports the size of the data the slice refers to, five i32 values at 4 bytes each.
A reference that carries extra information like this is called a fat pointer. The chapter on fat pointers covers it in more depth. For now, remember that a slice reference is cheap to create and to pass around, because only two words are copied and the elements are not.
Why `[T]` is unsized
The type [i32] has no size known at compile time, because different slices have different lengths. Rust calls such types dynamically sized types, or DSTs. This has practical consequences:
- You cannot declare a local variable of type
[i32], pass one by value, or return one by value.let s: [i32] = ...;is a compile error. - You can hold one only behind a pointer type that can carry the length:
&[T],&mut [T],Box<[T]>,Rc<[T]>, and similar. - Generic parameters assume
Sizedby default. To write a generic function that accepts[T]orstritself, you must opt out with?Sized.
In everyday code you rarely type [T] alone. You write &[T] and &mut [T].
Indexing and length
A slice has its own indices, starting at 0. Index 0 of a slice is the first element of the slice, not of the original collection.
fn main() {
let a = [10, 20, 30, 40, 50];
let s = &a[1..4];
println!("{}", s[0]);
println!("{}", s.len());
println!("{}", s.is_empty());
println!("{:?}", s.first());
println!("{:?}", s.last());
let empty = &a[2..2];
println!("{} {:?}", empty.is_empty(), empty.first());
}The output is:
20
3
false
Some(20)
Some(40)
true NonePoints to note:
s[0]isa[1]. The slice hides everything outside its range.len()is stored in the reference, so it takes constant time.- An empty slice is valid.
&a[2..2]is a legal slice of length 0, andfirst()returnsNonefor it. - Indexing with
s[i]panics wheni >= s.len(). Thegetmethod returns anOptioninstead. A later chapter covers this choice.
A slice is a borrow
Because a slice borrows from its owner, the usual borrowing rules apply to it. The owner cannot be moved, dropped, or mutated in a conflicting way while a slice of it is still in use.
fn main() {
let mut v = vec![1, 2, 3];
let s = &v[..2];
println!("{:?}", s);
v.push(4);
println!("{:?}", v);
}This compiles and prints [1, 2] and then [1, 2, 3, 4]. The borrow s ends after its last use, which is the first println!. After that point v.push(4) is allowed. If you added println!("{:?}", s); after the push, the compiler would reject the program with error E0502, "cannot borrow v as mutable because it is also borrowed as immutable."
The rule exists for a physical reason. push may need more room and may move the whole buffer to a new heap allocation. A slice created earlier would then point at freed memory. The borrow checker turns that risk into a compile-time error, so slices of a Vec are never left dangling.
The same idea applies to lifetimes. A slice cannot outlive its owner, so a function cannot return a slice of a local Vec it created. It can return a slice of its input, as first_word does in the later chapter on string slices.
Mutable slices
&mut [T] lets you change elements in place, but not change the length. A slice cannot grow or shrink the collection, since it has no access to the owner's capacity.
fn main() {
let mut a = [1, 2, 3, 4];
let s = &mut a[1..3];
s[0] = 20;
s[1] = 30;
println!("{:?}", a);
}This prints [1, 20, 30, 4]. Methods that rearrange elements, such as reverse, sort, and swap, are defined on [T]. They work on any array, Vec, or sub-range. Methods that change the length, such as push and insert, belong to Vec<T> and are not available on a slice. While a &mut slice is live, no other reference to the same elements may exist. A later chapter shows how split_at_mut gets two non-overlapping mutable slices out of one buffer.
Common mistakes
- Treating a slice as a copy. Writing through a
&mutslice changes the original. Reading through a&slice reflects later changes to the original, which the borrow checker prevents while the slice is alive. - Writing
&Vec<T>parameters. A&Vec<T>parameter accepts only vectors. A&[T]parameter accepts vectors, arrays, and sub-ranges, and it avoids a second pointer hop. - Confusing
[T]with&[T].[T]is the unsized sequence type.&[T]is the reference you can store and pass. Error messages such as "the size for values of type[i32]cannot be known at compilation time" mean you used[T]where a reference was needed. - Expecting the length to be part of the type. A
&[i32]can hold any number of elements. If you need the compiler to enforce an exact length, use an array reference such as&[i32; 3]. - Assuming a slice keeps data alive. A slice never extends an owner's life. If you need data that outlives its source, convert it to an owned type, as covered in the final chapter of this tutorial.
Summary of the working model
- A slice type
[T]describes consecutiveTvalues with a length known only at run time. - You hold it through a reference:
&[T]or&mut [T], each a pointer plus a length. - The owner stays an array, a
Vec, or another container, and the slice borrows from it. - The borrow checker keeps the owner valid and unmodified in conflicting ways for as long as the slice is used.
- Arrays and vectors convert to slices automatically at function boundaries, which makes
&[T]the natural parameter type.
Exercise
On a 64-bit target, size_of::<&u8>() returns 8 but size_of::<&[u8]>() returns 16. Why do they differ? Also, why does let s: [u8] = *bytes; (where bytes: &[u8]) fail to compile?
Show answer
A &u8 holds only the address of one byte. A &[u8] is a fat pointer: it holds the address of the first element plus the number of elements, two 8-byte words in total. The statement fails because [u8] is a dynamically sized type. Its size is unknown at compile time, so it cannot be stored in a local variable by value. You must keep it behind a reference such as &[u8].
Exercise
Given let mut v = vec![5, 6, 7, 8]; and let s = &v[1..3];, what does s[0] equal, and does the code println!("{:?}", s); v.push(9); println!("{:?}", s); compile?
Show answer
s[0] equals 6, because the slice starts at index 1 of v. The code does not compile. s is used again after v.push(9), so the shared borrow is still alive when push needs a mutable borrow, and the compiler reports error E0502. If the last println! of s is removed, the code compiles, because the borrow ends after the first print.