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
1.93.0 (const: 1.93.0) · Sourcepub const fn as_array<const N: usize>(&self) -> Option<&[T; N]>
pub const fn as_array<const N: usize>(&self) -> Option<&[T; N]>
Gets a reference to the underlying array.
If N is not exactly equal to the length of self, then this method returns None.
1.93.0 (const: 1.93.0) · Sourcepub const fn as_mut_array<const N: usize>(&mut self) -> Option<&mut [T; N]>
pub const fn as_mut_array<const N: usize>(&mut self) -> Option<&mut [T; N]>
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: 1.85.0) · Sourcepub const fn swap(&mut self, a: usize, b: usize)
pub const fn swap(&mut self, a: usize, b: usize)
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.0.0 (const: unstable) · Sourcepub fn windows(&self, size: usize) -> Windows<'_, T>
pub fn windows(&self, size: usize) -> Windows<'_, T>
Returns an iterator over all contiguous windows of length
size. The windows overlap. If the slice is shorter than
size, the iterator returns no values.
§Panics
Panics if size is zero.
§Examples
let slice = ['l', 'o', 'r', 'e', 'm'];
let mut iter = slice.windows(3);
assert_eq!(iter.next().unwrap(), &['l', 'o', 'r']);
assert_eq!(iter.next().unwrap(), &['o', 'r', 'e']);
assert_eq!(iter.next().unwrap(), &['r', 'e', 'm']);
assert!(iter.next().is_none());If the slice is shorter than size:
Because the Iterator trait cannot represent the required lifetimes,
there is no windows_mut analog to windows;
[0,1,2].windows_mut(2).collect() would violate the rules of references
(though a LendingIterator analog is possible). You can sometimes use
Cell::as_slice_of_cells in
conjunction with windows instead:
use std::cell::Cell;
let mut array = ['R', 'u', 's', 't', ' ', '2', '0', '1', '5'];
let slice = &mut array[..];
let slice_of_cells: &[Cell<char>] = Cell::from_mut(slice).as_slice_of_cells();
for w in slice_of_cells.windows(3) {
Cell::swap(&w[0], &w[2]);
}
assert_eq!(array, ['s', 't', ' ', '2', '0', '1', '5', 'u', 'R']);1.0.0 (const: unstable) · Sourcepub fn chunks(&self, chunk_size: usize) -> Chunks<'_, T>
pub fn chunks(&self, chunk_size: usize) -> Chunks<'_, T>
Returns an iterator over chunk_size elements of the slice at a time, starting at the
beginning of the slice.
The chunks are slices and do not overlap. If chunk_size does not divide the length of the
slice, then the last chunk will not have length chunk_size.
See chunks_exact for a variant of this iterator that returns chunks of always exactly
chunk_size elements, and rchunks for the same iterator but starting at the end of the
slice.
If your chunk_size is a constant, consider using as_chunks instead, which will
give references to arrays of exactly that length, rather than slices.
§Panics
Panics if chunk_size is zero.
§Examples
1.0.0 (const: unstable) · Sourcepub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<'_, T>
pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<'_, T>
Returns an iterator over chunk_size elements of the slice at a time, starting at the
beginning of the slice.
The chunks are mutable slices, and do not overlap. If chunk_size does not divide the
length of the slice, then the last chunk will not have length chunk_size.
See chunks_exact_mut for a variant of this iterator that returns chunks of always
exactly chunk_size elements, and rchunks_mut for the same iterator but starting at
the end of the slice.
If your chunk_size is a constant, consider using as_chunks_mut instead, which will
give references to arrays of exactly that length, rather than slices.
§Panics
Panics if chunk_size is zero.
§Examples
1.31.0 (const: unstable) · Sourcepub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, T>
pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, T>
Returns an iterator over chunk_size elements of the slice at a time, starting at the
beginning of the slice.
The chunks are slices and do not overlap. If chunk_size does not divide the length of the
slice, then the last up to chunk_size-1 elements will be omitted and can be retrieved
from the remainder function of the iterator.
Due to each chunk having exactly chunk_size elements, the compiler can often optimize the
resulting code better than in the case of chunks.
See chunks for a variant of this iterator that also returns the remainder as a smaller
chunk, and rchunks_exact for the same iterator but starting at the end of the slice.
If your chunk_size is a constant, consider using as_chunks instead, which will
give references to arrays of exactly that length, rather than slices.
§Panics
Panics if chunk_size is zero.
§Examples
1.31.0 (const: unstable) · Sourcepub fn chunks_exact_mut(&mut self, chunk_size: usize) -> ChunksExactMut<'_, T>
pub fn chunks_exact_mut(&mut self, chunk_size: usize) -> ChunksExactMut<'_, T>
Returns an iterator over chunk_size elements of the slice at a time, starting at the
beginning of the slice.
The chunks are mutable slices, and do not overlap. If chunk_size does not divide the
length of the slice, then the last up to chunk_size-1 elements will be omitted and can be
retrieved from the into_remainder function of the iterator.
Due to each chunk having exactly chunk_size elements, the compiler can often optimize the
resulting code better than in the case of chunks_mut.
See chunks_mut for a variant of this iterator that also returns the remainder as a
smaller chunk, and rchunks_exact_mut for the same iterator but starting at the end of
the slice.
If your chunk_size is a constant, consider using as_chunks_mut instead, which will
give references to arrays of exactly that length, rather than slices.
§Panics
Panics if chunk_size is zero.
§Examples
1.88.0 (const: 1.88.0) · Sourcepub const unsafe fn as_chunks_unchecked<const N: usize>(&self) -> &[[T; N]]
pub const unsafe fn as_chunks_unchecked<const N: usize>(&self) -> &[[T; N]]
Splits the slice into a slice of N-element arrays,
assuming that there’s no remainder.
This is the inverse operation to as_flattened.
As this is unsafe, consider whether you could use as_chunks or
as_rchunks instead, perhaps via something like
if let (chunks, []) = slice.as_chunks() or
let (chunks, []) = slice.as_chunks() else { unreachable!() };.
§Safety
This may only be called when
- The slice splits exactly into
N-element chunks (akaself.len() % N == 0). N != 0.
§Examples
let slice: &[char] = &['l', 'o', 'r', 'e', 'm', '!'];
let chunks: &[[char; 1]] =
// SAFETY: 1-element chunks never have remainder
unsafe { slice.as_chunks_unchecked() };
assert_eq!(chunks, &[['l'], ['o'], ['r'], ['e'], ['m'], ['!']]);
let chunks: &[[char; 3]] =
// SAFETY: The slice length (6) is a multiple of 3
unsafe { slice.as_chunks_unchecked() };
assert_eq!(chunks, &[['l', 'o', 'r'], ['e', 'm', '!']]);
// These would be unsound:
// let chunks: &[[_; 5]] = slice.as_chunks_unchecked() // The slice length is not a multiple of 5
// let chunks: &[[_; 0]] = slice.as_chunks_unchecked() // Zero-length chunks are never allowed1.88.0 (const: 1.88.0) · Sourcepub const fn as_chunks<const N: usize>(&self) -> (&[[T; N]], &[T])
pub const fn as_chunks<const N: usize>(&self) -> (&[[T; N]], &[T])
Splits the slice into a slice of N-element arrays,
starting at the beginning of the slice,
and a remainder slice with length strictly less than N.
The remainder is meaningful in the division sense. Given
let (chunks, remainder) = slice.as_chunks(), then:
chunks.len()equalsslice.len() / N,remainder.len()equalsslice.len() % N, andslice.len()equalschunks.len() * N + remainder.len().
You can flatten the chunks back into a slice-of-T with as_flattened.
§Panics
Panics if N is zero.
Note that this check is against a const generic parameter, not a runtime value, and thus a particular monomorphization will either always panic or it will never panic.
§Examples
let slice = ['l', 'o', 'r', 'e', 'm'];
let (chunks, remainder) = slice.as_chunks();
assert_eq!(chunks, &[['l', 'o'], ['r', 'e']]);
assert_eq!(remainder, &['m']);If you expect the slice to be an exact multiple, you can combine
let-else with an empty slice pattern:
1.0.0 (const: 1.71.0) · Sourcepub const fn split_at(&self, mid: usize) -> (&[T], &[T])
pub const fn split_at(&self, mid: usize) -> (&[T], &[T])
Divides one slice into two at an index.
The first will contain all indices from [0, mid) (excluding
the index mid itself) and the second will contain all
indices from [mid, len) (excluding the index len itself).
§Panics
Panics if mid > len. For a non-panicking alternative see
split_at_checked.
§Examples
let v = ['a', 'b', 'c'];
{
let (left, right) = v.split_at(0);
assert_eq!(left, []);
assert_eq!(right, ['a', 'b', 'c']);
}
{
let (left, right) = v.split_at(2);
assert_eq!(left, ['a', 'b']);
assert_eq!(right, ['c']);
}
{
let (left, right) = v.split_at(3);
assert_eq!(left, ['a', 'b', 'c']);
assert_eq!(right, []);
}1.0.0 (const: 1.83.0) · Sourcepub const fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T])
pub const fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T])
Divides one mutable slice into two at an index.
The first will contain all indices from [0, mid) (excluding
the index mid itself) and the second will contain all
indices from [mid, len) (excluding the index len itself).
§Panics
Panics if mid > len. For a non-panicking alternative see
split_at_mut_checked.
§Examples
1.79.0 (const: 1.77.0) · Sourcepub const unsafe fn split_at_unchecked(&self, mid: usize) -> (&[T], &[T])
pub const unsafe fn split_at_unchecked(&self, mid: usize) -> (&[T], &[T])
Divides one slice into two at an index, without doing bounds checking.
The first will contain all indices from [0, mid) (excluding
the index mid itself) and the second will contain all
indices from [mid, len) (excluding the index len itself).
For a safe alternative see split_at.
§Safety
Calling this method with an out-of-bounds index is undefined behavior
even if the resulting reference is not used. The caller has to ensure that
0 <= mid <= self.len().
§Examples
let v = ['a', 'b', 'c'];
unsafe {
let (left, right) = v.split_at_unchecked(0);
assert_eq!(left, []);
assert_eq!(right, ['a', 'b', 'c']);
}
unsafe {
let (left, right) = v.split_at_unchecked(2);
assert_eq!(left, ['a', 'b']);
assert_eq!(right, ['c']);
}
unsafe {
let (left, right) = v.split_at_unchecked(3);
assert_eq!(left, ['a', 'b', 'c']);
assert_eq!(right, []);
}1.79.0 (const: 1.83.0) · Sourcepub const unsafe fn split_at_mut_unchecked(
&mut self,
mid: usize,
) -> (&mut [T], &mut [T])
pub const unsafe fn split_at_mut_unchecked( &mut self, mid: usize, ) -> (&mut [T], &mut [T])
Divides one mutable slice into two at an index, without doing bounds checking.
The first will contain all indices from [0, mid) (excluding
the index mid itself) and the second will contain all
indices from [mid, len) (excluding the index len itself).
For a safe alternative see split_at_mut.
§Safety
Calling this method with an out-of-bounds index is undefined behavior
even if the resulting reference is not used. The caller has to ensure that
0 <= mid <= self.len().
§Examples
1.80.0 (const: 1.80.0) · Sourcepub const fn split_at_checked(&self, mid: usize) -> Option<(&[T], &[T])>
pub const fn split_at_checked(&self, mid: usize) -> Option<(&[T], &[T])>
Divides one slice into two at an index, returning None if the slice is
too short.
If mid ≤ len returns a pair of slices where the first will contain all
indices from [0, mid) (excluding the index mid itself) and the
second will contain all indices from [mid, len) (excluding the index
len itself).
Otherwise, if mid > len, returns None.
§Examples
let v = [1, -2, 3, -4, 5, -6];
{
let (left, right) = v.split_at_checked(0).unwrap();
assert_eq!(left, []);
assert_eq!(right, [1, -2, 3, -4, 5, -6]);
}
{
let (left, right) = v.split_at_checked(2).unwrap();
assert_eq!(left, [1, -2]);
assert_eq!(right, [3, -4, 5, -6]);
}
{
let (left, right) = v.split_at_checked(6).unwrap();
assert_eq!(left, [1, -2, 3, -4, 5, -6]);
assert_eq!(right, []);
}
assert_eq!(None, v.split_at_checked(7));1.80.0 (const: 1.83.0) · Sourcepub const fn split_at_mut_checked(
&mut self,
mid: usize,
) -> Option<(&mut [T], &mut [T])>
pub const fn split_at_mut_checked( &mut self, mid: usize, ) -> Option<(&mut [T], &mut [T])>
Divides one mutable slice into two at an index, returning None if the
slice is too short.
If mid ≤ len returns a pair of slices where the first will contain all
indices from [0, mid) (excluding the index mid itself) and the
second will contain all indices from [mid, len) (excluding the index
len itself).
Otherwise, if mid > len, returns None.
§Examples
1.0.0 · Sourcepub fn starts_with(&self, needle: &[T]) -> boolwhere
T: PartialEq,
pub fn starts_with(&self, needle: &[T]) -> boolwhere
T: PartialEq,
Returns true if needle is a prefix of the slice or equal to the slice.
§Examples
let v = [10, 40, 30];
assert!(v.starts_with(&[10]));
assert!(v.starts_with(&[10, 40]));
assert!(v.starts_with(&v));
assert!(!v.starts_with(&[50]));
assert!(!v.starts_with(&[10, 50]));Always returns true if needle is an empty slice:
1.26.0 (const: 1.92.0) · Sourcepub const fn rotate_left(&mut self, mid: usize)
pub const fn rotate_left(&mut self, mid: usize)
Rotates the slice in-place such that the first mid elements of the
slice move to the end while the last self.len() - mid elements move to
the front.
After calling rotate_left, the element previously at index mid will
become the first element in the slice.
§Panics
This function will panic if mid is greater than the length of the
slice. Note that mid == self.len() does not panic and is a no-op
rotation.
§Complexity
Takes linear (in self.len()) time.
§Examples
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
a.rotate_left(2);
assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);Rotating a subslice:
1.26.0 (const: 1.92.0) · Sourcepub const fn rotate_right(&mut self, k: usize)
pub const fn rotate_right(&mut self, k: usize)
Rotates the slice in-place such that the first self.len() - k
elements of the slice move to the end while the last k elements move
to the front.
After calling rotate_right, the element previously at index
self.len() - k will become the first element in the slice.
§Panics
This function will panic if k is greater than the length of the
slice. Note that k == self.len() does not panic and is a no-op
rotation.
§Complexity
Takes linear (in self.len()) time.
§Examples
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
a.rotate_right(2);
assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);Rotating a subslice:
1.50.0 · Sourcepub fn fill(&mut self, value: T)where
T: Clone,
pub fn fill(&mut self, value: T)where
T: Clone,
Fills self with elements by cloning value.
§Examples
1.7.0 · Sourcepub fn clone_from_slice(&mut self, src: &[T])where
T: Clone,
pub fn clone_from_slice(&mut self, src: &[T])where
T: Clone,
Copies the elements from src into self.
The length of src must be the same as self.
§Panics
This function will panic if the two slices have different lengths.
§Examples
Cloning 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.clone_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 clone_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:
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:
1.30.0 · Sourcepub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T])
pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T])
Transmutes the slice to a slice of another type, ensuring alignment of the types is maintained.
This method splits the slice into three distinct slices: prefix, correctly aligned middle slice of a new type, and the suffix slice. The middle part will be as big as possible under the given alignment constraint and element size.
This method has no purpose when either input element T or output element U are
zero-sized and will return the original slice without splitting anything.
§Safety
This method is essentially a transmute with respect to the elements in the returned
middle slice, so all the usual caveats pertaining to transmute::<T, U> also apply here.
§Examples
Basic usage:
1.30.0 · Sourcepub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T])
pub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T])
Transmutes the mutable slice to a mutable slice of another type, ensuring alignment of the types is maintained.
This method splits the slice into three distinct slices: prefix, correctly aligned middle slice of a new type, and the suffix slice. The middle part will be as big as possible under the given alignment constraint and element size.
This method has no purpose when either input element T or output element U are
zero-sized and will return the original slice without splitting anything.
§Safety
This method is essentially a transmute with respect to the elements in the returned
middle slice, so all the usual caveats pertaining to transmute::<T, U> also apply here.
§Examples
Basic usage:
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.