Rust Reference ยท Primitive Types
Rust slices: the [T] type
Reference for Rust slices: the unsized [T] type, &[T] and &mut [T] views, range slicing, split_at_mut, fat pointers, panics and slice patterns.
A slice is a view into a contiguous run of elements. The type [T] has no length known to the compiler, so you can never hold one by value; you always use it behind a pointer: &[T] (shared), &mut [T] (exclusive), Box<[T]> or Rc<[T]>. A reference to a slice is a "fat pointer" made of an address and a length.
Slices are how Rust code accepts "some elements" without caring where they live. An array, a Vec<T>, a part of either, and even a String's bytes can all be passed to a function that takes &[T].
let v = vec![1, 2, 3, 4, 5]; let middle: &[i32] = &v[1..4];
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
&v[a..b] // elements a up to (not including) b &v[a..=b] // a through b &v[..] // everything &mut v[a..] // mutable view let s: &[T] = &array; // coercion from &[T; N] or &Vec<T>
| Part | Description |
|---|---|
a, b |
usize positions. Either may be omitted. |
| Result | &[T] or &mut [T], borrowing the original for as long as the slice is alive. |
Panics: &v[a..b] panics if a > b or b > len. get(range) returns None instead, and get_mut does the same for mutable access.
Usage notes
- Take
&[T]in parameters rather than&Vec<T>or&[T; N]: callers can pass any of them, and the function still reads the elements the same way. - Borrowing rules apply. While a slice of a
Vecexists you cannot push to the vector, because that may reallocate and leave the slice dangling. The compiler enforces this. - Disjoint mutable access:
split_at_mut,chunks_mut,split_first_mutanditer_mutgive several&mutpieces that provably do not overlap. Two&mut v[..]expressions do not compile. - Zero-length slices are valid:
&v[len..]is an empty slice and does not panic. stris a slice too.&stris a view into UTF-8 bytes, and slicing it by byte range panics if you cut inside a character (seestr).- Sorting, searching and chunking are all slice methods:
sort,binary_search,windowsandchunks. - Owned boxed slices:
Vec::into_boxed_slicegives aBox<[T]>that drops spare capacity. - Equality and order compare element by element, so
[1, 2][..] == vec![1, 2][..]works across array and vector sources.
Related
[T; N] arrays,Vec<T>,str,Slice patterns,Sorting slices- Lessons: Slices, Arrays, Borrowing