Primitive Type slice
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.
Implementations§
Source§impl<T> [MaybeUninit<T>]
impl<T> [MaybeUninit<T>]
Sourcepub const unsafe fn assume_init_drop(&mut self)where
T:,
🔬This is a nightly-only experimental API. (maybe_uninit_slice #63569)
pub const unsafe fn assume_init_drop(&mut self)where
T:,
maybe_uninit_slice #63569)Drops the contained values in place.
§Safety
It is up to the caller to guarantee that every MaybeUninit<T> in the slice
really is in an initialized state. Calling this when the content is not yet
fully initialized causes undefined behavior.
On top of that, all additional invariants of the type T must be
satisfied, as the Drop implementation of T (or its members) may
rely on this. For example, setting a Vec<T> to an invalid but
non-null address makes it initialized (under the current implementation;
this does not constitute a stable guarantee), because the only
requirement the compiler knows about it is that the data pointer must be
non-null. Dropping such a Vec<T> however will cause undefined
behaviour.
Sourcepub const unsafe fn assume_init_ref(&self) -> &[T]
🔬This is a nightly-only experimental API. (maybe_uninit_slice #63569)
pub const unsafe fn assume_init_ref(&self) -> &[T]
maybe_uninit_slice #63569)Gets a shared reference to the contained value.
§Safety
Calling this when the content is not yet fully initialized causes undefined
behavior: it is up to the caller to guarantee that every MaybeUninit<T> in
the slice really is in an initialized state.
Source§impl<T> [T]
impl<T> [T]
1.0.0 (const: 1.39.0) · Sourcepub const fn is_empty(&self) -> bool
pub const fn is_empty(&self) -> bool
Returns true if the slice has a length of 0.
§Examples
1.0.0 (const: 1.56.0) · Sourcepub const fn first(&self) -> Option<&T>
pub const fn first(&self) -> Option<&T>
Returns the first element of the slice, or None if it is empty.
§Examples
1.0.0 (const: 1.83.0) · Sourcepub const fn first_mut(&mut self) -> Option<&mut T>
pub const fn first_mut(&mut self) -> Option<&mut T>
Returns a mutable reference to the first element of the slice, or None if it is empty.
§Examples
1.5.0 (const: 1.56.0) · Sourcepub const fn split_first(&self) -> Option<(&T, &[T])>
pub const fn split_first(&self) -> Option<(&T, &[T])>
Returns the first and all the rest of the elements of the slice, or None if it is empty.
§Examples
1.5.0 (const: 1.83.0) · Sourcepub const fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])>
pub const fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])>
Returns the first and all the rest of the elements of the slice, or None if it is empty.
§Examples
1.5.0 (const: 1.56.0) · Sourcepub const fn split_last(&self) -> Option<(&T, &[T])>
pub const fn split_last(&self) -> Option<(&T, &[T])>
Returns the last and all the rest of the elements of the slice, or None if it is empty.
§Examples
1.5.0 (const: 1.83.0) · Sourcepub const fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])>
pub const fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])>
Returns the last and all the rest of the elements of the slice, or None if it is empty.
§Examples
1.0.0 (const: 1.56.0) · Sourcepub const fn last(&self) -> Option<&T>
pub const fn last(&self) -> Option<&T>
Returns the last element of the slice, or None if it is empty.
§Examples
1.0.0 (const: 1.83.0) · Sourcepub const fn last_mut(&mut self) -> Option<&mut T>
pub const fn last_mut(&mut self) -> Option<&mut T>
Returns a mutable reference to the last item in the slice, or None if it is empty.
§Examples
1.77.0 (const: 1.77.0) · Sourcepub const fn first_chunk<const N: usize>(&self) -> Option<&[T; N]>
pub const fn first_chunk<const N: usize>(&self) -> Option<&[T; N]>
Returns an array reference to the first N items in the slice.
If the slice is not at least N in length, this will return None.
§Examples
1.77.0 (const: 1.83.0) · Sourcepub const fn first_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]>
pub const fn first_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]>
Returns a mutable array reference to the first N items in the slice.
If the slice is not at least N in length, this will return None.
§Examples
1.0.0 (const: unstable) · Sourcepub fn get<I>(&self, index: I) -> Option<&I::Output>where
I: SliceIndex<Self>,
pub fn get<I>(&self, index: I) -> Option<&I::Output>where
I: SliceIndex<Self>,
Returns a reference to an element or subslice depending on the type of index.
- If given a position, returns a reference to the element at that
position or
Noneif out of bounds. - If given a range, returns the subslice corresponding to that range,
or
Noneif out of bounds.
§Examples
1.0.0 (const: unstable) · Sourcepub fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>where
I: SliceIndex<Self>,
pub fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>where
I: SliceIndex<Self>,
1.0.0 (const: unstable) · Sourcepub unsafe fn get_unchecked<I>(&self, index: I) -> &I::Outputwhere
I: SliceIndex<Self>,
pub unsafe fn get_unchecked<I>(&self, index: I) -> &I::Outputwhere
I: SliceIndex<Self>,
Returns a reference to an element or subslice, without doing bounds checking.
For a safe alternative see get.
§Safety
Calling this method with an out-of-bounds index is undefined behavior even if the resulting reference is not used.
You can think of this like .get(index).unwrap_unchecked(). It’s UB
to call .get_unchecked(len), even if you immediately convert to a
pointer. And it’s UB to call .get_unchecked(..len + 1),
.get_unchecked(..=len), or similar.
§Examples
1.0.0 (const: unstable) · Sourcepub unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Outputwhere
I: SliceIndex<Self>,
pub unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Outputwhere
I: SliceIndex<Self>,
Returns a mutable reference to an element or subslice, without doing bounds checking.
For a safe alternative see get_mut.
§Safety
Calling this method with an out-of-bounds index is undefined behavior even if the resulting reference is not used.
You can think of this like .get_mut(index).unwrap_unchecked(). It’s
UB to call .get_unchecked_mut(len), even if you immediately convert
to a pointer. And it’s UB to call .get_unchecked_mut(..len + 1),
.get_unchecked_mut(..=len), or similar.
§Examples
1.0.0 (const: 1.32.0) · Sourcepub const fn as_ptr(&self) -> *const T
pub const fn as_ptr(&self) -> *const T
Returns a raw pointer to the slice’s buffer.
The caller must ensure that the slice outlives the pointer this function returns, or else it will end up dangling.
The caller must also ensure that the memory the pointer (non-transitively) points to
is never written to (except inside an UnsafeCell) using this pointer or any pointer
derived from it. If you need to mutate the contents of the slice, use as_mut_ptr.
Modifying the container referenced by this slice may cause its buffer to be reallocated, which would also make any pointers to it invalid.
§Examples
1.0.0 (const: 1.61.0) · Sourcepub const fn as_mut_ptr(&mut self) -> *mut T
pub const fn as_mut_ptr(&mut self) -> *mut T
Returns an unsafe mutable pointer to the slice’s buffer.
The caller must ensure that the slice outlives the pointer this function returns, or else it will end up dangling.
Modifying the container referenced by this slice may cause its buffer to be reallocated, which would also make any pointers to it invalid.
§Examples
Sourcepub const fn as_array<const N: usize>(&self) -> Option<&[T; N]>
🔬This is a nightly-only experimental API. (slice_as_array #133508)
pub const fn as_array<const N: usize>(&self) -> Option<&[T; N]>
slice_as_array #133508)Gets a reference to the underlying array.
If N is not exactly equal to the length of self, then this method returns None.
Sourcepub const fn as_mut_array<const N: usize>(&mut self) -> Option<&mut [T; N]>
🔬This is a nightly-only experimental API. (slice_as_array #133508)
pub const fn as_mut_array<const N: usize>(&mut self) -> Option<&mut [T; N]>
slice_as_array #133508)Gets a mutable reference to the slice’s underlying array.
If N is not exactly equal to the length of self, then this method returns None.
1.0.0 (const: unstable) · Sourcepub fn iter(&self) -> Iter<'_, T>
pub fn iter(&self) -> Iter<'_, T>
1.0.0 (const: unstable) · Sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
pub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns an iterator that allows modifying each value.
The iterator yields all items from start to end.
§Examples
1.9.0 (const: 1.87.0) · Sourcepub const fn copy_from_slice(&mut self, src: &[T])where
T: Copy,
pub const fn copy_from_slice(&mut self, src: &[T])where
T: Copy,
Copies all elements from src into self, using a memcpy.
The length of src must be the same as self.
If T does not implement Copy, use clone_from_slice.
§Panics
This function will panic if the two slices have different lengths.
§Examples
Copying two elements from a slice into another:
let src = [1, 2, 3, 4];
let mut dst = [0, 0];
// Because the slices have to be the same length,
// we slice the source slice from four elements
// to two. It will panic if we don't do this.
dst.copy_from_slice(&src[2..]);
assert_eq!(src, [1, 2, 3, 4]);
assert_eq!(dst, [3, 4]);Rust enforces that there can only be one mutable reference with no
immutable references to a particular piece of data in a particular
scope. Because of this, attempting to use copy_from_slice on a
single slice will result in a compile failure:
To work around this, we can use split_at_mut to create two distinct
sub-slices from a slice:
Trait Implementations§
1.0.0 · Source§impl<'a, T> IntoIterator for &'a [T]
impl<'a, T> IntoIterator for &'a [T]
1.0.0 · Source§impl<'a, T> IntoIterator for &'a mut [T]
impl<'a, T> IntoIterator for &'a mut [T]
1.0.0 (const: unstable) · Source§impl<T, U, const N: usize> PartialEq<&[U]> for [T; N]where
T: PartialEq<U>,
impl<T, U, const N: usize> PartialEq<&[U]> for [T; N]where
T: PartialEq<U>,
1.0.0 (const: unstable) · Source§impl<T, U, const N: usize> PartialEq<&mut [U]> for [T; N]where
T: PartialEq<U>,
impl<T, U, const N: usize> PartialEq<&mut [U]> for [T; N]where
T: PartialEq<U>,
1.0.0 (const: unstable) · Source§impl<T, U, const N: usize> PartialEq<[U]> for [T; N]where
T: PartialEq<U>,
impl<T, U, const N: usize> PartialEq<[U]> for [T; N]where
T: PartialEq<U>,
1.0.0 (const: unstable) · Source§impl<T, U, const N: usize> PartialEq<[U; N]> for &[T]where
T: PartialEq<U>,
impl<T, U, const N: usize> PartialEq<[U; N]> for &[T]where
T: PartialEq<U>,
1.0.0 (const: unstable) · Source§impl<T, U, const N: usize> PartialEq<[U; N]> for &mut [T]where
T: PartialEq<U>,
impl<T, U, const N: usize> PartialEq<[U; N]> for &mut [T]where
T: PartialEq<U>,
1.0.0 (const: unstable) · Source§impl<T, U, const N: usize> PartialEq<[U; N]> for [T]where
T: PartialEq<U>,
impl<T, U, const N: usize> PartialEq<[U; N]> for [T]where
T: PartialEq<U>,
1.53.0 · Source§impl<T> SliceIndex<[T]> for (Bound<usize>, Bound<usize>)
impl<T> SliceIndex<[T]> for (Bound<usize>, Bound<usize>)
Source§fn get(self, slice: &[T]) -> Option<&Self::Output>
fn get(self, slice: &[T]) -> Option<&Self::Output>
slice_index_methods)Source§fn get_mut(self, slice: &mut [T]) -> Option<&mut Self::Output>
fn get_mut(self, slice: &mut [T]) -> Option<&mut Self::Output>
slice_index_methods)Source§unsafe fn get_unchecked(self, slice: *const [T]) -> *const Self::Output
unsafe fn get_unchecked(self, slice: *const [T]) -> *const Self::Output
slice_index_methods)Source§unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut Self::Output
unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut Self::Output
slice_index_methods)1.15.0 (const: unstable) · Source§impl<T> SliceIndex<[T]> for Range<usize>
The methods index and index_mut panic if:
impl<T> SliceIndex<[T]> for Range<usize>
The methods index and index_mut panic if:
- the start of the range is greater than the end of the range or
- the end of the range is out of bounds.
Source§fn get(self, slice: &[T]) -> Option<&[T]>
fn get(self, slice: &[T]) -> Option<&[T]>
slice_index_methods)Source§fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]>
fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]>
slice_index_methods)Source§unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T]
unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T]
slice_index_methods)Source§unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T]
unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T]
slice_index_methods)1.15.0 (const: unstable) · Source§impl<T> SliceIndex<[T]> for RangeFrom<usize>
The methods index and index_mut panic if the start of the range is out of bounds.
impl<T> SliceIndex<[T]> for RangeFrom<usize>
The methods index and index_mut panic if the start of the range is out of bounds.
Source§fn get(self, slice: &[T]) -> Option<&[T]>
fn get(self, slice: &[T]) -> Option<&[T]>
slice_index_methods)Source§fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]>
fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]>
slice_index_methods)Source§unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T]
unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T]
slice_index_methods)Source§unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T]
unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T]
slice_index_methods)1.15.0 (const: unstable) · Source§impl<T> SliceIndex<[T]> for RangeFull
impl<T> SliceIndex<[T]> for RangeFull
Source§fn get(self, slice: &[T]) -> Option<&[T]>
fn get(self, slice: &[T]) -> Option<&[T]>
slice_index_methods)Source§fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]>
fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]>
slice_index_methods)Source§unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T]
unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T]
slice_index_methods)Source§unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T]
unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T]
slice_index_methods)1.26.0 (const: unstable) · Source§impl<T> SliceIndex<[T]> for RangeInclusive<usize>
The methods index and index_mut panic if:
impl<T> SliceIndex<[T]> for RangeInclusive<usize>
The methods index and index_mut panic if:
- the end of the range is
usize::MAXor - the start of the range is greater than the end of the range or
- the end of the range is out of bounds.
Source§fn get(self, slice: &[T]) -> Option<&[T]>
fn get(self, slice: &[T]) -> Option<&[T]>
slice_index_methods)Source§fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]>
fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]>
slice_index_methods)Source§unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T]
unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T]
slice_index_methods)Source§unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T]
unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T]
slice_index_methods)1.15.0 (const: unstable) · Source§impl<T> SliceIndex<[T]> for RangeTo<usize>
The methods index and index_mut panic if the end of the range is out of bounds.
impl<T> SliceIndex<[T]> for RangeTo<usize>
The methods index and index_mut panic if the end of the range is out of bounds.
Source§fn get(self, slice: &[T]) -> Option<&[T]>
fn get(self, slice: &[T]) -> Option<&[T]>
slice_index_methods)Source§fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]>
fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]>
slice_index_methods)Source§unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T]
unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T]
slice_index_methods)Source§unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T]
unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T]
slice_index_methods)1.26.0 (const: unstable) · Source§impl<T> SliceIndex<[T]> for RangeToInclusive<usize>
The methods index and index_mut panic if the end of the range is out of bounds.
impl<T> SliceIndex<[T]> for RangeToInclusive<usize>
The methods index and index_mut panic if the end of the range is out of bounds.
Source§fn get(self, slice: &[T]) -> Option<&[T]>
fn get(self, slice: &[T]) -> Option<&[T]>
slice_index_methods)Source§fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]>
fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]>
slice_index_methods)Source§unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T]
unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T]
slice_index_methods)Source§unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T]
unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T]
slice_index_methods)1.15.0 (const: unstable) · Source§impl<T> SliceIndex<[T]> for usize
The methods index and index_mut panic if the index is out of bounds.
impl<T> SliceIndex<[T]> for usize
The methods index and index_mut panic if the index is out of bounds.
Source§fn get(self, slice: &[T]) -> Option<&T>
fn get(self, slice: &[T]) -> Option<&T>
slice_index_methods)Source§fn get_mut(self, slice: &mut [T]) -> Option<&mut T>
fn get_mut(self, slice: &mut [T]) -> Option<&mut T>
slice_index_methods)Source§unsafe fn get_unchecked(self, slice: *const [T]) -> *const T
unsafe fn get_unchecked(self, slice: *const [T]) -> *const T
slice_index_methods)Source§unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut T
unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut T
slice_index_methods)1.34.0 (const: unstable) · Source§impl<'a, T, const N: usize> TryFrom<&'a [T]> for &'a [T; N]
Tries to create an array ref &[T; N] from a slice ref &[T]. Succeeds if
slice.len() == N.
impl<'a, T, const N: usize> TryFrom<&'a [T]> for &'a [T; N]
Tries to create an array ref &[T; N] from a slice ref &[T]. Succeeds if
slice.len() == N.
1.34.0 (const: unstable) · Source§impl<T, const N: usize> TryFrom<&[T]> for [T; N]where
T: Copy,
Tries to create an array [T; N] by copying from a slice &[T].
Succeeds if slice.len() == N.
impl<T, const N: usize> TryFrom<&[T]> for [T; N]where
T: Copy,
Tries to create an array [T; N] by copying from a slice &[T].
Succeeds if slice.len() == N.
1.34.0 (const: unstable) · Source§impl<'a, T, const N: usize> TryFrom<&'a mut [T]> for &'a mut [T; N]
Tries to create a mutable array ref &mut [T; N] from a mutable slice ref
&mut [T]. Succeeds if slice.len() == N.
impl<'a, T, const N: usize> TryFrom<&'a mut [T]> for &'a mut [T; N]
Tries to create a mutable array ref &mut [T; N] from a mutable slice ref
&mut [T]. Succeeds if slice.len() == N.
1.59.0 (const: unstable) · Source§impl<T, const N: usize> TryFrom<&mut [T]> for [T; N]where
T: Copy,
Tries to create an array [T; N] by copying from a mutable slice &mut [T].
Succeeds if slice.len() == N.
impl<T, const N: usize> TryFrom<&mut [T]> for [T; N]where
T: Copy,
Tries to create an array [T; N] by copying from a mutable slice &mut [T].
Succeeds if slice.len() == N.