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"];
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]);
It is possible to slice empty subranges of slices by using empty ranges (including slice.len()..slice.len()
):
let x = [1, 2, 3];
let empty = &x[0..0]; // subslice before the first element
assert_eq!(empty, &[]);
let empty = &x[..0]; // same as &x[0..0]
assert_eq!(empty, &[]);
let empty = &x[1..1]; // empty subslice in the middle
assert_eq!(empty, &[]);
let empty = &x[3..3]; // subslice after the last element
assert_eq!(empty, &[]);
let empty = &x[3..]; // same as &x[3..3]
assert_eq!(empty, &[]);
It is not allowed to use subranges that start with lower bound bigger than slice.len()
:
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 = size_of::<&u8>();
assert_eq!(2 * pointer_size, size_of::<&[u8]>());
assert_eq!(2 * pointer_size, size_of::<*const [u8]>());
assert_eq!(2 * pointer_size, size_of::<Box<[u8]>>());
assert_eq!(2 * pointer_size, size_of::<Rc<[u8]>>());
§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.
The mutable slice yields mutable references to the elements:
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
.