Module std::prim_slice

1.0.0 · source ·
Expand description

A dynamically-sized view into a contiguous sequence, [T]. Contiguous here means that elements are laid out so that every element is the same distance from its neighbors.

See also the std::slice module.

Slices are a view into a block of memory represented as a pointer and a length.

// slicing a Vec
let vec = vec![1, 2, 3];
let int_slice = &vec[..];
// coercing an array to a slice
let str_slice: &[&str] = &["one", "two", "three"];
Run

Slices are either mutable or shared. The shared slice type is &[T], while the mutable slice type is &mut [T], where T represents the element type. For example, you can mutate the block of memory that a mutable slice points to:

let mut x = [1, 2, 3];
let x = &mut x[..]; // Take a full slice of `x`.
x[1] = 7;
assert_eq!(x, &[1, 7, 3]);
Run

As slices store the length of the sequence they refer to, they have twice the size of pointers to Sized types. Also see the reference on dynamically sized types.

let pointer_size = std::mem::size_of::<&u8>();
assert_eq!(2 * pointer_size, std::mem::size_of::<&[u8]>());
assert_eq!(2 * pointer_size, std::mem::size_of::<*const [u8]>());
assert_eq!(2 * pointer_size, std::mem::size_of::<Box<[u8]>>());
assert_eq!(2 * pointer_size, std::mem::size_of::<Rc<[u8]>>());
Run

Trait Implementations

Some traits are implemented for slices if the element type implements that trait. This includes Eq, Hash and Ord.

Iteration

The slices implement IntoIterator. The iterator yields references to the slice elements.

let numbers: &[i32] = &[0, 1, 2];
for n in numbers {
    println!("{n} is a number!");
}
Run

The mutable slice yields mutable references to the elements:

let mut scores: &mut [i32] = &mut [7, 8, 9];
for score in scores {
    *score += 1;
}
Run

This iterator yields mutable references to the slice’s elements, so while the element type of the slice is i32, the element type of the iterator is &mut i32.