Rust Arrays, Vectors and Slices Slices


Slices are views into a list of objects, and have type [T], indicating a slice of objects with type T.

A slice is an unsized type, and therefore can only be used behind a pointer. (String world analogy: str, called string slice, is also unsized.)

Arrays get coerced into slices, and vectors can be dereferenced to slices. Therefore, slice methods can be applied to both of them. (String world analogy: str is to String, what [T] is to Vec<T>.)

fn main() {
    let vector = vec![1, 2, 3, 4, 5, 6, 7, 8];
    let slice = &vector[3..6];
    println!("length of slice: {}", slice.len()); // 3
    println!("slice: {:?}", slice); // [4, 5, 6]