跳到主要内容

BorrowedPayload

结构体 BorrowedPayload 

Source
pub struct BorrowedPayload<'a>(/* private fields */);

实现§

Source§

impl<'a> BorrowedPayload<'a>

Source

pub fn truncate(&mut self, len: usize)

Methods from Deref<Target = [u8]>§

1.23.0 · Source

pub fn is_ascii(&self) -> bool

检查此切片中的所有字节是否都在 ASCII 范围内。

空切片返回 true

Source

pub fn as_ascii(&self) -> Option<&[AsciiChar]>

🔬This is a nightly-only experimental API. (ascii_char)

If this slice is_ascii, returns it as 一个 slice of ASCII characters, otherwise returns None

Source

pub unsafe fn as_ascii_unchecked(&self) -> &[AsciiChar]

🔬This is a nightly-only experimental API. (ascii_char)

Converts this slice of bytes into 一个 slice of ASCII characters, without checking whether they’re valid.

§Safety

Every byte in the slice must be in 0.。=127, 或 else this is UB.

1.23.0 · Source

pub fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool

Checks that two slices are an ASCII case-insensitive match.

Same as to_ascii_lowercase(一个) == to_ascii_lowercase(b), but without allocating 并 copying temporaries.

1.23.0 · Source

pub fn make_ascii_uppercase(&mut self)

Converts this slice 到 its ASCII upper case equivalent in-place.

ASCII letters ‘一个’ 到 ‘z’ are mapped 到 ‘A’ 到 ‘Z’, but non-ASCII letters are unchanged.

To return 新 uppercased value without modifying the existing one, use to_ascii_uppercase

1.23.0 · Source

pub fn make_ascii_lowercase(&mut self)

Converts this slice 到 its ASCII lower case equivalent in-place.

ASCII letters ‘A’ 到 ‘Z’ are mapped 到 ‘一个’ 到 ‘z’, but non-ASCII letters are unchanged.

To return 新 lowercased value without modifying the existing one, use to_ascii_lowercase

1.60.0 · Source

pub fn escape_ascii(&self) -> EscapeAscii<'_>

Returns an iterator that produces an escaped version of this slice, treating it as an ASCII string.

§示例
let s = b"0\t\r\n'\"\\\x9d";
let escaped = s.escape_ascii().to_string();
assert_eq!(escaped, "0\\t\\r\\n\\'\\\"\\\\\\x9d");
1.80.0 · Source

pub fn trim_ascii_start(&self) -> &[u8]

Returns 一个 byte slice with leading ASCII whitespace bytes removed.

‘Whitespace’ refers 到 the definition 用于 u8::is_ascii_whitespace

§示例
assert_eq!(b" \t hello world\n".trim_ascii_start(), b"hello world\n");
assert_eq!(b"  ".trim_ascii_start(), b"");
assert_eq!(b"".trim_ascii_start(), b"");
1.80.0 · Source

pub fn trim_ascii_end(&self) -> &[u8]

Returns 一个 byte slice with trailing ASCII whitespace bytes removed.

‘Whitespace’ refers 到 the definition 用于 u8::is_ascii_whitespace

§示例
assert_eq!(b"\r hello world\n ".trim_ascii_end(), b"\r hello world");
assert_eq!(b"  ".trim_ascii_end(), b"");
assert_eq!(b"".trim_ascii_end(), b"");
1.80.0 · Source

pub fn trim_ascii(&self) -> &[u8]

Returns 一个 byte slice with leading 并 trailing ASCII whitespace bytes removed.

‘Whitespace’ refers 到 the definition 用于 u8::is_ascii_whitespace

§示例
assert_eq!(b"\r hello world\n ".trim_ascii(), b"hello world");
assert_eq!(b"  ".trim_ascii(), b"");
assert_eq!(b"".trim_ascii(), b"");
1.0.0 · Source

pub fn len(&self) -> usize

返回数量 elements in the slice.

§示例
let a = [1, 2, 3];
assert_eq!(a.len(), 3);
1.0.0 · Source

pub fn is_empty(&self) -> bool

Returns true if the slice has 一个 length of 0.

§示例
let a = [1, 2, 3];
assert!(!a.is_empty());

let b: &[i32] = &[];
assert!(b.is_empty());
1.0.0 · Source

pub fn first(&self) -> Option<&T>

Returns the first element of the slice, 或 None if it is empty.

§示例
let v = [10, 40, 30];
assert_eq!(Some(&10), v.first());

let w: &[i32] = &[];
assert_eq!(None, w.first());
1.0.0 · Source

pub fn first_mut(&mut self) -> Option<&mut T>

Returns 一个 mutable reference 到 the first element of the slice, 或 None if it is empty.

§示例
let x = &mut [0, 1, 2];

if let Some(first) = x.first_mut() {
    *first = 5;
}
assert_eq!(x, &[5, 1, 2]);

let y: &mut [i32] = &mut [];
assert_eq!(None, y.first_mut());
1.5.0 · Source

pub fn split_first(&self) -> Option<(&T, &[T])>

Returns the first 并 all the rest of the elements of the slice, 或 None if it is empty.

§示例
let x = &[0, 1, 2];

if let Some((first, elements)) = x.split_first() {
    assert_eq!(first, &0);
    assert_eq!(elements, &[1, 2]);
}
1.5.0 · Source

pub fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])>

Returns the first 并 all the rest of the elements of the slice, 或 None if it is empty.

§示例
let x = &mut [0, 1, 2];

if let Some((first, elements)) = x.split_first_mut() {
    *first = 3;
    elements[0] = 4;
    elements[1] = 5;
}
assert_eq!(x, &[3, 4, 5]);
1.5.0 · Source

pub fn split_last(&self) -> Option<(&T, &[T])>

Returns the last 并 all the rest of the elements of the slice, 或 None if it is empty.

§示例
let x = &[0, 1, 2];

if let Some((last, elements)) = x.split_last() {
    assert_eq!(last, &2);
    assert_eq!(elements, &[0, 1]);
}
1.5.0 · Source

pub fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])>

Returns the last 并 all the rest of the elements of the slice, 或 None if it is empty.

§示例
let x = &mut [0, 1, 2];

if let Some((last, elements)) = x.split_last_mut() {
    *last = 3;
    elements[0] = 4;
    elements[1] = 5;
}
assert_eq!(x, &[4, 5, 3]);
1.0.0 · Source

pub fn last(&self) -> Option<&T>

Returns the last element of the slice, 或 None if it is empty.

§示例
let v = [10, 40, 30];
assert_eq!(Some(&30), v.last());

let w: &[i32] = &[];
assert_eq!(None, w.last());
1.0.0 · Source

pub fn last_mut(&mut self) -> Option<&mut T>

Returns 一个 mutable reference 到 the last item in the slice, 或 None if it is empty.

§示例
let x = &mut [0, 1, 2];

if let Some(last) = x.last_mut() {
    *last = 10;
}
assert_eq!(x, &[0, 1, 10]);

let y: &mut [i32] = &mut [];
assert_eq!(None, y.last_mut());
1.77.0 · Source

pub fn first_chunk<const N: usize>(&self) -> Option<&[T; N]>

Returns an array reference 到 the first N items in the slice.

If the slice is not at least N in length, this 将返回 None

§示例
let u = [10, 40, 30];
assert_eq!(Some(&[10, 40]), u.first_chunk::<2>());

let v: &[i32] = &[10];
assert_eq!(None, v.first_chunk::<2>());

let w: &[i32] = &[];
assert_eq!(Some(&[]), w.first_chunk::<0>());
1.77.0 · Source

pub fn first_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]>

Returns 一个 mutable array reference 到 the first N items in the slice.

If the slice is not at least N in length, this 将返回 None

§示例
let x = &mut [0, 1, 2];

if let Some(first) = x.first_chunk_mut::<2>() {
    first[0] = 5;
    first[1] = 4;
}
assert_eq!(x, &[5, 4, 2]);

assert_eq!(None, x.first_chunk_mut::<4>());
1.77.0 · Source

pub fn split_first_chunk<const N: usize>(&self) -> Option<(&[T; N], &[T])>

Returns an array reference 到 the first N items in the slice 并 the remaining slice.

If the slice is not at least N in length, this 将返回 None

§示例
let x = &[0, 1, 2];

if let Some((first, elements)) = x.split_first_chunk::<2>() {
    assert_eq!(first, &[0, 1]);
    assert_eq!(elements, &[2]);
}

assert_eq!(None, x.split_first_chunk::<4>());
1.77.0 · Source

pub fn split_first_chunk_mut<const N: usize>( &mut self, ) -> Option<(&mut [T; N], &mut [T])>

Returns 一个 mutable array reference 到 the first N items in the slice 并 the remaining slice.

If the slice is not at least N in length, this 将返回 None

§示例
let x = &mut [0, 1, 2];

if let Some((first, elements)) = x.split_first_chunk_mut::<2>() {
    first[0] = 3;
    first[1] = 4;
    elements[0] = 5;
}
assert_eq!(x, &[3, 4, 5]);

assert_eq!(None, x.split_first_chunk_mut::<4>());
1.77.0 · Source

pub fn split_last_chunk<const N: usize>(&self) -> Option<(&[T], &[T; N])>

Returns an array reference 到 the last N items in the slice 并 the remaining slice.

If the slice is not at least N in length, this 将返回 None

§示例
let x = &[0, 1, 2];

if let Some((elements, last)) = x.split_last_chunk::<2>() {
    assert_eq!(elements, &[0]);
    assert_eq!(last, &[1, 2]);
}

assert_eq!(None, x.split_last_chunk::<4>());
1.77.0 · Source

pub fn split_last_chunk_mut<const N: usize>( &mut self, ) -> Option<(&mut [T], &mut [T; N])>

Returns 一个 mutable array reference 到 the last N items in the slice 并 the remaining slice.

If the slice is not at least N in length, this 将返回 None

§示例
let x = &mut [0, 1, 2];

if let Some((elements, last)) = x.split_last_chunk_mut::<2>() {
    last[0] = 3;
    last[1] = 4;
    elements[0] = 5;
}
assert_eq!(x, &[5, 3, 4]);

assert_eq!(None, x.split_last_chunk_mut::<4>());
1.77.0 · Source

pub fn last_chunk<const N: usize>(&self) -> Option<&[T; N]>

Returns an array reference 到 the last N items in the slice.

If the slice is not at least N in length, this 将返回 None

§示例
let u = [10, 40, 30];
assert_eq!(Some(&[40, 30]), u.last_chunk::<2>());

let v: &[i32] = &[10];
assert_eq!(None, v.last_chunk::<2>());

let w: &[i32] = &[];
assert_eq!(Some(&[]), w.last_chunk::<0>());
1.77.0 · Source

pub fn last_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]>

Returns 一个 mutable array reference 到 the last N items in the slice.

If the slice is not at least N in length, this 将返回 None

§示例
let x = &mut [0, 1, 2];

if let Some(last) = x.last_chunk_mut::<2>() {
    last[0] = 10;
    last[1] = 20;
}
assert_eq!(x, &[0, 10, 20]);

assert_eq!(None, x.last_chunk_mut::<4>());
1.0.0 · Source

pub fn get<I>(&self, index: I) -> Option<&<I as SliceIndex<[T]>>::Output>
where I: SliceIndex<[T]>,

Returns 一个 reference 到 an element 或 subslice depending on the type of index.

  • If given a position, returns a reference to the element at that position or None if out of bounds.
  • If given a range, returns the subslice corresponding to that range, or None if out of bounds.
§示例
let v = [10, 40, 30];
assert_eq!(Some(&40), v.get(1));
assert_eq!(Some(&[10, 40][..]), v.get(0..2));
assert_eq!(None, v.get(3));
assert_eq!(None, v.get(0..4));
1.0.0 · Source

pub fn get_mut<I>( &mut self, index: I, ) -> Option<&mut <I as SliceIndex<[T]>>::Output>
where I: SliceIndex<[T]>,

Returns 一个 mutable reference 到 an element 或 subslice depending on the type of index (see get) 或 None if the index is out of bounds.

§示例
let x = &mut [0, 1, 2];

if let Some(elem) = x.get_mut(1) {
    *elem = 42;
}
assert_eq!(x, &[0, 42, 2]);
1.0.0 · Source

pub unsafe fn get_unchecked<I>( &self, index: I, ) -> &<I as SliceIndex<[T]>>::Output
where I: SliceIndex<[T]>,

Returns 一个 reference 到 an element 或 subslice, without doing bounds checking.

For 一个 safe alternative see get

§Safety

调用 this method with an out-of-bounds index is undefined behavior even if the resulting reference is not 用.

You can think of this like .get(index).unwrap_unchecked()。 It’s UB 到 call .get_unchecked(len), even if you immediately convert 到 一个 pointer. And it’s UB 到 call .get_unchecked(。.len + 1), .get_unchecked(。。=len), 或 similar.

§示例
let x = &[1, 2, 4];

unsafe {
    assert_eq!(x.get_unchecked(1), &2);
}
1.0.0 · Source

pub unsafe fn get_unchecked_mut<I>( &mut self, index: I, ) -> &mut <I as SliceIndex<[T]>>::Output
where I: SliceIndex<[T]>,

Returns 一个 mutable reference 到 an element 或 subslice, without doing bounds checking.

For 一个 safe alternative see get_mut

§Safety

调用 this method with an out-of-bounds index is undefined behavior even if the resulting reference is not 用.

You can think of this like .get_mut(index).unwrap_unchecked()。 It’s UB 到 call .get_unchecked_mut(len), even if you immediately convert 到 一个 pointer. And it’s UB 到 call .get_unchecked_mut(。.len + 1), .get_unchecked_mut(。。=len), 或 similar.

§示例
let x = &mut [1, 2, 4];

unsafe {
    let elem = x.get_unchecked_mut(1);
    *elem = 13;
}
assert_eq!(x, &[1, 13, 4]);
1.0.0 · Source

pub fn as_ptr(&self) -> *const T

Returns 一个 raw pointer 到 the slice’s 缓冲区.

此 caller must ensure that the slice outlives the pointer this function returns, 或 else it will end up dangling.

此 caller must also ensure that the memory the pointer (non-transitively) points 到 is never written 到 (except inside an UnsafeCell) using this pointer 或 any pointer derived 从 it. If you need 到 mutate the contents of the slice, use as_mut_ptr

Modifying the container referenced by this slice may cause its 缓冲区 到 be reallocated, which would also make any pointers 到 it invalid.

§示例
let x = &[1, 2, 4];
let x_ptr = x.as_ptr();

unsafe {
    for i in 0..x.len() {
        assert_eq!(x.get_unchecked(i), &*x_ptr.add(i));
    }
}
1.0.0 · Source

pub fn as_mut_ptr(&mut self) -> *mut T

Returns an unsafe mutable pointer 到 the slice’s 缓冲区.

此 caller must ensure that the slice outlives the pointer this function returns, 或 else it will end up dangling.

Modifying the container referenced by this slice may cause its 缓冲区 到 be reallocated, which would also make any pointers 到 it invalid.

§示例
let x = &mut [1, 2, 4];
let x_ptr = x.as_mut_ptr();

unsafe {
    for i in 0..x.len() {
        *x_ptr.add(i) += 2;
    }
}
assert_eq!(x, &[3, 4, 6]);
1.48.0 · Source

pub fn as_ptr_range(&self) -> Range<*const T>

Returns the two raw pointers spanning the slice.

此 returned range is half-open, which means that the end pointer points one past the last element of the slice. This way, an empty slice is represented by two equal pointers, 并 the difference between the two pointers represents the size of the slice.

,请参见as_ptr 用于 warnings on using these pointers. 此 end pointer requires extra caution, as it does not point 到 一个 valid element in the slice.

This function is useful 用于 interacting with foreign interfaces which use two pointers 到 refer 到 一个 range of elements in memory, as is common in C++。

It can also be useful 到 检查 if 一个 pointer 到 an element refers 到 an element of this slice:

let a = [1, 2, 3];
let x = &a[1] as *const _;
let y = &5 as *const _;

assert!(a.as_ptr_range().contains(&x));
assert!(!a.as_ptr_range().contains(&y));
1.48.0 · Source

pub fn as_mut_ptr_range(&mut self) -> Range<*mut T>

Returns the two unsafe mutable pointers spanning the slice.

此 returned range is half-open, which means that the end pointer points one past the last element of the slice. This way, an empty slice is represented by two equal pointers, 并 the difference between the two pointers represents the size of the slice.

,请参见as_mut_ptr 用于 warnings on using these pointers. 此 end pointer requires extra caution, as it does not point 到 一个 valid element in the slice.

This function is useful 用于 interacting with foreign interfaces which use two pointers 到 refer 到 一个 range of elements in memory, as is common in C++。

1.93.0 · Source

pub fn as_array<const N: usize>(&self) -> Option<&[T; N]>

Gets 一个 reference 到 底层 array.

If N is not exactly equal 到 the length of self, then this method returns None

1.93.0 · Source

pub fn as_mut_array<const N: usize>(&mut self) -> Option<&mut [T; N]>

Gets 一个 mutable reference 到 the slice’s underlying array.

If N is not exactly equal 到 the length of self, then this method returns None

1.0.0 · Source

pub fn swap(&mut self, a: usize, b: usize)

Swaps two elements in the slice.

If 一个 equals 到 b, it’s guaranteed that elements won’t change value.

§Arguments
  • a - The index of the first element
  • b - The index of the second element
§Panics

Panics if 一个b are out of bounds.

§示例
let mut v = ["a", "b", "c", "d", "e"];
v.swap(2, 4);
assert!(v == ["a", "b", "e", "d", "c"]);
Source

pub unsafe fn swap_unchecked(&mut self, a: usize, b: usize)

🔬This is a nightly-only experimental API. (slice_swap_unchecked)

Swaps two elements in the slice, without doing bounds checking.

For 一个 safe alternative see swap

§Arguments
  • a - The index of the first element
  • b - The index of the second element
§Safety

调用 this method with an out-of-bounds index is undefined behavior。 此 caller has 到 ensure that 一个 < self.len()b < self.len()

§示例
#![feature(slice_swap_unchecked)]

let mut v = ["a", "b", "c", "d"];
// SAFETY: we know that 1 and 3 are both indices of the slice
unsafe { v.swap_unchecked(1, 3) };
assert!(v == ["a", "d", "c", "b"]);
1.0.0 · Source

pub fn reverse(&mut self)

Reverses the order of elements in the slice, in place.

§示例
let mut v = [1, 2, 3];
v.reverse();
assert!(v == [3, 2, 1]);
1.0.0 · Source

pub fn iter(&self) -> Iter<'_, T>

Returns an iterator over the slice.

此 iterator yields all items 从 start 到 end.

§示例
let x = &[1, 2, 4];
let mut iterator = x.iter();

assert_eq!(iterator.next(), Some(&1));
assert_eq!(iterator.next(), Some(&2));
assert_eq!(iterator.next(), Some(&4));
assert_eq!(iterator.next(), None);
1.0.0 · Source

pub fn iter_mut(&mut self) -> IterMut<'_, T>

Returns an iterator that allows modifying each value.

此 iterator yields all items 从 start 到 end.

§示例
let x = &mut [1, 2, 4];
for elem in x.iter_mut() {
    *elem += 2;
}
assert_eq!(x, &[3, 4, 6]);
1.0.0 · Source

pub fn windows(&self, size: usize) -> Windows<'_, T>

Returns an iterator over all contiguous windows of length size。 此 windows overlap. If the slice is shorter than size, the iterator returns no values.

§Panics

Panics if size is zero.

§示例
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:

let slice = ['f', 'o', 'o'];
let mut iter = slice.windows(4);
assert!(iter.next().is_none());

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 · Source

pub fn chunks(&self, chunk_size: usize) -> Chunks<'_, T>

Returns an iterator over chunk_size elements of the slice at 一个 time, starting at the beginning of the slice.

此 chunks are slices 并 do not overlap. If chunk_size does not divide the length of the slice, then the last chunk will not have length chunk_size

,请参见chunks_exact 用于 一个 variant of this iterator that returns chunks of always exactly chunk_size elements, 并 rchunks 用于 the same iterator but starting at the end of the slice.

If your chunk_size 是 constant, consider using as_chunks instead, which will give references 到 arrays of exactly that length, rather than slices.

§Panics

Panics if chunk_size is zero.

§示例
let slice = ['l', 'o', 'r', 'e', 'm'];
let mut iter = slice.chunks(2);
assert_eq!(iter.next().unwrap(), &['l', 'o']);
assert_eq!(iter.next().unwrap(), &['r', 'e']);
assert_eq!(iter.next().unwrap(), &['m']);
assert!(iter.next().is_none());
1.0.0 · Source

pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<'_, T>

Returns an iterator over chunk_size elements of the slice at 一个 time, starting at the beginning of the slice.

此 chunks are mutable slices, 并 do not overlap. If chunk_size does not divide the length of the slice, then the last chunk will not have length chunk_size

,请参见chunks_exact_mut 用于 一个 variant of this iterator that returns chunks of always exactly chunk_size elements, 并 rchunks_mut 用于 the same iterator but starting at the end of the slice.

If your chunk_size 是 constant, consider using as_chunks_mut instead, which will give references 到 arrays of exactly that length, rather than slices.

§Panics

Panics if chunk_size is zero.

§示例
let v = &mut [0, 0, 0, 0, 0];
let mut count = 1;

for chunk in v.chunks_mut(2) {
    for elem in chunk.iter_mut() {
        *elem += count;
    }
    count += 1;
}
assert_eq!(v, &[1, 1, 2, 2, 3]);
1.31.0 · Source

pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, T>

Returns an iterator over chunk_size elements of the slice at 一个 time, starting at the beginning of the slice.

此 chunks are slices 并 do not overlap. If chunk_size does not divide the length of the slice, then the last up 到 chunk_size-1 elements , omitted 并 can be retrieved 从 the remainder function of the iterator.

Due 到 each chunk having exactly chunk_size elements, the compiler can often optimize the resulting code better than in the case of chunks

,请参见chunks 用于 一个 variant of this iterator that also returns the remainder as 一个 smaller chunk, 并 rchunks_exact 用于 the same iterator but starting at the end of the slice.

If your chunk_size 是 constant, consider using as_chunks instead, which will give references 到 arrays of exactly that length, rather than slices.

§Panics

Panics if chunk_size is zero.

§示例
let slice = ['l', 'o', 'r', 'e', 'm'];
let mut iter = slice.chunks_exact(2);
assert_eq!(iter.next().unwrap(), &['l', 'o']);
assert_eq!(iter.next().unwrap(), &['r', 'e']);
assert!(iter.next().is_none());
assert_eq!(iter.remainder(), &['m']);
1.31.0 · Source

pub fn chunks_exact_mut(&mut self, chunk_size: usize) -> ChunksExactMut<'_, T>

Returns an iterator over chunk_size elements of the slice at 一个 time, starting at the beginning of the slice.

此 chunks are mutable slices, 并 do not overlap. If chunk_size does not divide the length of the slice, then the last up 到 chunk_size-1 elements , omitted 并 can be retrieved 从 the into_remainder function of the iterator.

Due 到 each chunk having exactly chunk_size elements, the compiler can often optimize the resulting code better than in the case of chunks_mut

,请参见chunks_mut 用于 一个 variant of this iterator that also returns the remainder as 一个 smaller chunk, 并 rchunks_exact_mut 用于 the same iterator but starting at the end of the slice.

If your chunk_size 是 constant, consider using as_chunks_mut instead, which will give references 到 arrays of exactly that length, rather than slices.

§Panics

Panics if chunk_size is zero.

§示例
let v = &mut [0, 0, 0, 0, 0];
let mut count = 1;

for chunk in v.chunks_exact_mut(2) {
    for elem in chunk.iter_mut() {
        *elem += count;
    }
    count += 1;
}
assert_eq!(v, &[1, 1, 2, 2, 0]);
1.88.0 · Source

pub unsafe fn as_chunks_unchecked<const N: usize>(&self) -> &[[T; N]]

Splits the slice into 一个 slice of N-element arrays, assuming that there’s no remainder.

This 是 inverse operation 到 as_flattened

As this is unsafe, consider whether you could use as_chunksas_rchunks instead, perhaps via something like if let (chunks, []) = slice.as_chunks()let (chunks, []) = slice.as_chunks() else { unreachable!() };

§Safety

This may only be called when

  • The slice splits exactly into N-element chunks (aka self.len() % N == 0).
  • N != 0.
§示例
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 allowed
1.88.0 · Source

pub fn as_chunks<const N: usize>(&self) -> (&[[T; N]], &[T])

Splits the slice into 一个 slice of N-element arrays, starting at the beginning of the slice, 并 一个 remainder slice with length strictly less than N

此 remainder is meaningful in the division sense. Given let (chunks, remainder) = slice.as_chunks(), then:

  • chunks.len() equals slice.len() / N,
  • remainder.len() equals slice.len() % N, and
  • slice.len() equals chunks.len() * N + remainder.len().

You can flatten the chunks back into 一个 slice-of-T with as_flattened

§Panics

Panics if N is zero.

Note that this 检查 is against 一个 const generic parameter, not 一个 runtime value, 并 thus 一个 particular monomorphization will either always panic 或 it will never panic.

§示例
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:

let slice = ['R', 'u', 's', 't'];
let (chunks, []) = slice.as_chunks::<2>() else {
    panic!("slice didn't have even length")
};
assert_eq!(chunks, &[['R', 'u'], ['s', 't']]);
1.88.0 · Source

pub fn as_rchunks<const N: usize>(&self) -> (&[T], &[[T; N]])

Splits the slice into 一个 slice of N-element arrays, starting at the end of the slice, 并 一个 remainder slice with length strictly less than N

此 remainder is meaningful in the division sense. Given let (remainder, chunks) = slice.as_rchunks(), then:

  • remainder.len() equals slice.len() % N,
  • chunks.len() equals slice.len() / N, and
  • slice.len() equals chunks.len() * N + remainder.len().

You can flatten the chunks back into 一个 slice-of-T with as_flattened

§Panics

Panics if N is zero.

Note that this 检查 is against 一个 const generic parameter, not 一个 runtime value, 并 thus 一个 particular monomorphization will either always panic 或 it will never panic.

§示例
let slice = ['l', 'o', 'r', 'e', 'm'];
let (remainder, chunks) = slice.as_rchunks();
assert_eq!(remainder, &['l']);
assert_eq!(chunks, &[['o', 'r'], ['e', 'm']]);
1.88.0 · Source

pub unsafe fn as_chunks_unchecked_mut<const N: usize>( &mut self, ) -> &mut [[T; N]]

Splits the slice into 一个 slice of N-element arrays, assuming that there’s no remainder.

This 是 inverse operation 到 as_flattened_mut

As this is unsafe, consider whether you could use as_chunks_mutas_rchunks_mut instead, perhaps via something like if let (chunks, []) = slice.as_chunks_mut()let (chunks, []) = slice.as_chunks_mut() else { unreachable!() };

§Safety

This may only be called when

  • The slice splits exactly into N-element chunks (aka self.len() % N == 0).
  • N != 0.
§示例
let slice: &mut [char] = &mut ['l', 'o', 'r', 'e', 'm', '!'];
let chunks: &mut [[char; 1]] =
    // SAFETY: 1-element chunks never have remainder
    unsafe { slice.as_chunks_unchecked_mut() };
chunks[0] = ['L'];
assert_eq!(chunks, &[['L'], ['o'], ['r'], ['e'], ['m'], ['!']]);
let chunks: &mut [[char; 3]] =
    // SAFETY: The slice length (6) is a multiple of 3
    unsafe { slice.as_chunks_unchecked_mut() };
chunks[1] = ['a', 'x', '?'];
assert_eq!(slice, &['L', 'o', 'r', 'a', 'x', '?']);

// These would be unsound:
// let chunks: &[[_; 5]] = slice.as_chunks_unchecked_mut() // The slice length is not a multiple of 5
// let chunks: &[[_; 0]] = slice.as_chunks_unchecked_mut() // Zero-length chunks are never allowed
1.88.0 · Source

pub fn as_chunks_mut<const N: usize>(&mut self) -> (&mut [[T; N]], &mut [T])

Splits the slice into 一个 slice of N-element arrays, starting at the beginning of the slice, 并 一个 remainder slice with length strictly less than N

此 remainder is meaningful in the division sense. Given let (chunks, remainder) = slice.as_chunks_mut(), then:

  • chunks.len() equals slice.len() / N,
  • remainder.len() equals slice.len() % N, and
  • slice.len() equals chunks.len() * N + remainder.len().

You can flatten the chunks back into 一个 slice-of-T with as_flattened_mut

§Panics

Panics if N is zero.

Note that this 检查 is against 一个 const generic parameter, not 一个 runtime value, 并 thus 一个 particular monomorphization will either always panic 或 it will never panic.

§示例
let v = &mut [0, 0, 0, 0, 0];
let mut count = 1;

let (chunks, remainder) = v.as_chunks_mut();
remainder[0] = 9;
for chunk in chunks {
    *chunk = [count; 2];
    count += 1;
}
assert_eq!(v, &[1, 1, 2, 2, 9]);
1.88.0 · Source

pub fn as_rchunks_mut<const N: usize>(&mut self) -> (&mut [T], &mut [[T; N]])

Splits the slice into 一个 slice of N-element arrays, starting at the end of the slice, 并 一个 remainder slice with length strictly less than N

此 remainder is meaningful in the division sense. Given let (remainder, chunks) = slice.as_rchunks_mut(), then:

  • remainder.len() equals slice.len() % N,
  • chunks.len() equals slice.len() / N, and
  • slice.len() equals chunks.len() * N + remainder.len().

You can flatten the chunks back into 一个 slice-of-T with as_flattened_mut

§Panics

Panics if N is zero.

Note that this 检查 is against 一个 const generic parameter, not 一个 runtime value, 并 thus 一个 particular monomorphization will either always panic 或 it will never panic.

§示例
let v = &mut [0, 0, 0, 0, 0];
let mut count = 1;

let (remainder, chunks) = v.as_rchunks_mut();
remainder[0] = 9;
for chunk in chunks {
    *chunk = [count; 2];
    count += 1;
}
assert_eq!(v, &[9, 1, 1, 2, 2]);
1.94.0 · Source

pub fn array_windows<const N: usize>(&self) -> ArrayWindows<'_, T, N>

Returns an iterator over overlapping windows of N elements of 一个 slice, starting at the beginning of the slice.

This 是 const generic equivalent of windows

If N is greater than the size of the slice, it 将返回 no windows.

§Panics

Panics if N is zero.

Note that this 检查 is against 一个 const generic parameter, not 一个 runtime value, 并 thus 一个 particular monomorphization will either always panic 或 it will never panic.

§示例
let slice = [0, 1, 2, 3];
let mut iter = slice.array_windows();
assert_eq!(iter.next().unwrap(), &[0, 1]);
assert_eq!(iter.next().unwrap(), &[1, 2]);
assert_eq!(iter.next().unwrap(), &[2, 3]);
assert!(iter.next().is_none());
1.31.0 · Source

pub fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T>

Returns an iterator over chunk_size elements of the slice at 一个 time, starting at the end of the slice.

此 chunks are slices 并 do not overlap. If chunk_size does not divide the length of the slice, then the last chunk will not have length chunk_size

,请参见rchunks_exact 用于 一个 variant of this iterator that returns chunks of always exactly chunk_size elements, 并 chunks 用于 the same iterator but starting at the beginning of the slice.

If your chunk_size 是 constant, consider using as_rchunks instead, which will give references 到 arrays of exactly that length, rather than slices.

§Panics

Panics if chunk_size is zero.

§示例
let slice = ['l', 'o', 'r', 'e', 'm'];
let mut iter = slice.rchunks(2);
assert_eq!(iter.next().unwrap(), &['e', 'm']);
assert_eq!(iter.next().unwrap(), &['o', 'r']);
assert_eq!(iter.next().unwrap(), &['l']);
assert!(iter.next().is_none());
1.31.0 · Source

pub fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<'_, T>

Returns an iterator over chunk_size elements of the slice at 一个 time, starting at the end of the slice.

此 chunks are mutable slices, 并 do not overlap. If chunk_size does not divide the length of the slice, then the last chunk will not have length chunk_size

,请参见rchunks_exact_mut 用于 一个 variant of this iterator that returns chunks of always exactly chunk_size elements, 并 chunks_mut 用于 the same iterator but starting at the beginning of the slice.

If your chunk_size 是 constant, consider using as_rchunks_mut instead, which will give references 到 arrays of exactly that length, rather than slices.

§Panics

Panics if chunk_size is zero.

§示例
let v = &mut [0, 0, 0, 0, 0];
let mut count = 1;

for chunk in v.rchunks_mut(2) {
    for elem in chunk.iter_mut() {
        *elem += count;
    }
    count += 1;
}
assert_eq!(v, &[3, 2, 2, 1, 1]);
1.31.0 · Source

pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, T>

Returns an iterator over chunk_size elements of the slice at 一个 time, starting at the end of the slice.

此 chunks are slices 并 do not overlap. If chunk_size does not divide the length of the slice, then the last up 到 chunk_size-1 elements , omitted 并 can be retrieved 从 the remainder function of the iterator.

Due 到 each chunk having exactly chunk_size elements, the compiler can often optimize the resulting code better than in the case of rchunks

,请参见rchunks 用于 一个 variant of this iterator that also returns the remainder as 一个 smaller chunk, 并 chunks_exact 用于 the same iterator but starting at the beginning of the slice.

If your chunk_size 是 constant, consider using as_rchunks instead, which will give references 到 arrays of exactly that length, rather than slices.

§Panics

Panics if chunk_size is zero.

§示例
let slice = ['l', 'o', 'r', 'e', 'm'];
let mut iter = slice.rchunks_exact(2);
assert_eq!(iter.next().unwrap(), &['e', 'm']);
assert_eq!(iter.next().unwrap(), &['o', 'r']);
assert!(iter.next().is_none());
assert_eq!(iter.remainder(), &['l']);
1.31.0 · Source

pub fn rchunks_exact_mut(&mut self, chunk_size: usize) -> RChunksExactMut<'_, T>

Returns an iterator over chunk_size elements of the slice at 一个 time, starting at the end of the slice.

此 chunks are mutable slices, 并 do not overlap. If chunk_size does not divide the length of the slice, then the last up 到 chunk_size-1 elements , omitted 并 can be retrieved 从 the into_remainder function of the iterator.

Due 到 each chunk having exactly chunk_size elements, the compiler can often optimize the resulting code better than in the case of chunks_mut

,请参见rchunks_mut 用于 一个 variant of this iterator that also returns the remainder as 一个 smaller chunk, 并 chunks_exact_mut 用于 the same iterator but starting at the beginning of the slice.

If your chunk_size 是 constant, consider using as_rchunks_mut instead, which will give references 到 arrays of exactly that length, rather than slices.

§Panics

Panics if chunk_size is zero.

§示例
let v = &mut [0, 0, 0, 0, 0];
let mut count = 1;

for chunk in v.rchunks_exact_mut(2) {
    for elem in chunk.iter_mut() {
        *elem += count;
    }
    count += 1;
}
assert_eq!(v, &[0, 2, 2, 1, 1]);
1.77.0 · Source

pub fn chunk_by<F>(&self, pred: F) -> ChunkBy<'_, T, F>
where F: FnMut(&T, &T) -> bool,

Returns an iterator over the slice producing non-overlapping runs of elements using the predicate 到 separate them.

此 predicate is called 用于 every pair of consecutive elements, meaning that it is called on slice[0]slice[1], followed by slice[1]slice[2], 并 so on.

§示例
let slice = &[1, 1, 1, 3, 3, 2, 2, 2];

let mut iter = slice.chunk_by(|a, b| a == b);

assert_eq!(iter.next(), Some(&[1, 1, 1][..]));
assert_eq!(iter.next(), Some(&[3, 3][..]));
assert_eq!(iter.next(), Some(&[2, 2, 2][..]));
assert_eq!(iter.next(), None);

This method can be used to extract the sorted subslices:

let slice = &[1, 1, 2, 3, 2, 3, 2, 3, 4];

let mut iter = slice.chunk_by(|a, b| a <= b);

assert_eq!(iter.next(), Some(&[1, 1, 2, 3][..]));
assert_eq!(iter.next(), Some(&[2, 3][..]));
assert_eq!(iter.next(), Some(&[2, 3, 4][..]));
assert_eq!(iter.next(), None);
1.77.0 · Source

pub fn chunk_by_mut<F>(&mut self, pred: F) -> ChunkByMut<'_, T, F>
where F: FnMut(&T, &T) -> bool,

Returns an iterator over the slice producing non-overlapping mutable runs of elements using the predicate 到 separate them.

此 predicate is called 用于 every pair of consecutive elements, meaning that it is called on slice[0]slice[1], followed by slice[1]slice[2], 并 so on.

§示例
let slice = &mut [1, 1, 1, 3, 3, 2, 2, 2];

let mut iter = slice.chunk_by_mut(|a, b| a == b);

assert_eq!(iter.next(), Some(&mut [1, 1, 1][..]));
assert_eq!(iter.next(), Some(&mut [3, 3][..]));
assert_eq!(iter.next(), Some(&mut [2, 2, 2][..]));
assert_eq!(iter.next(), None);

This method can be used to extract the sorted subslices:

let slice = &mut [1, 1, 2, 3, 2, 3, 2, 3, 4];

let mut iter = slice.chunk_by_mut(|a, b| a <= b);

assert_eq!(iter.next(), Some(&mut [1, 1, 2, 3][..]));
assert_eq!(iter.next(), Some(&mut [2, 3][..]));
assert_eq!(iter.next(), Some(&mut [2, 3, 4][..]));
assert_eq!(iter.next(), None);
1.0.0 · Source

pub fn split_at(&self, mid: usize) -> (&[T], &[T])

Divides one slice into two at an index.

此 first will contain all indices 从 [0, mid) (excluding the index mid itself) 并 the second will contain all indices 从 [mid, len) (excluding the index len itself)。

§Panics

Panics if mid > len。 For 一个 non-panicking alternative see split_at_checked

§示例
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 · Source

pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T])

Divides one mutable slice into two at an index.

此 first will contain all indices 从 [0, mid) (excluding the index mid itself) 并 the second will contain all indices 从 [mid, len) (excluding the index len itself)。

§Panics

Panics if mid > len。 For 一个 non-panicking alternative see split_at_mut_checked

§示例
let mut v = [1, 0, 3, 0, 5, 6];
let (left, right) = v.split_at_mut(2);
assert_eq!(left, [1, 0]);
assert_eq!(right, [3, 0, 5, 6]);
left[1] = 2;
right[1] = 4;
assert_eq!(v, [1, 2, 3, 4, 5, 6]);
1.79.0 · Source

pub unsafe fn split_at_unchecked(&self, mid: usize) -> (&[T], &[T])

Divides one slice into two at an index, without doing bounds checking.

此 first will contain all indices 从 [0, mid) (excluding the index mid itself) 并 the second will contain all indices 从 [mid, len) (excluding the index len itself)。

For 一个 safe alternative see split_at

§Safety

调用 this method with an out-of-bounds index is undefined behavior even if the resulting reference is not 用. 此 caller has 到 ensure that 0 <= mid <= self.len()

§示例
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 · Source

pub 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.

此 first will contain all indices 从 [0, mid) (excluding the index mid itself) 并 the second will contain all indices 从 [mid, len) (excluding the index len itself)。

For 一个 safe alternative see split_at_mut

§Safety

调用 this method with an out-of-bounds index is undefined behavior even if the resulting reference is not 用. 此 caller has 到 ensure that 0 <= mid <= self.len()

§示例
let mut v = [1, 0, 3, 0, 5, 6];
// scoped to restrict the lifetime of the borrows
unsafe {
    let (left, right) = v.split_at_mut_unchecked(2);
    assert_eq!(left, [1, 0]);
    assert_eq!(right, [3, 0, 5, 6]);
    left[1] = 2;
    right[1] = 4;
}
assert_eq!(v, [1, 2, 3, 4, 5, 6]);
1.80.0 · Source

pub 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 一个 pair of slices where the first will contain all indices 从 [0, mid) (excluding the index mid itself) 并 the second will contain all indices 从 [mid, len) (excluding the index len itself)。

Otherwise, if mid > len, returns None

§示例
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 · Source

pub 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 一个 pair of slices where the first will contain all indices 从 [0, mid) (excluding the index mid itself) 并 the second will contain all indices 从 [mid, len) (excluding the index len itself)。

Otherwise, if mid > len, returns None

§示例
let mut v = [1, 0, 3, 0, 5, 6];

if let Some((left, right)) = v.split_at_mut_checked(2) {
    assert_eq!(left, [1, 0]);
    assert_eq!(right, [3, 0, 5, 6]);
    left[1] = 2;
    right[1] = 4;
}
assert_eq!(v, [1, 2, 3, 4, 5, 6]);

assert_eq!(None, v.split_at_mut_checked(7));
1.0.0 · Source

pub fn split<F>(&self, pred: F) -> Split<'_, T, F>
where F: FnMut(&T) -> bool,

Returns an iterator over subslices separated by elements that match pred。 此 matched element is not contained in the subslices.

§示例
let slice = [10, 40, 33, 20];
let mut iter = slice.split(|num| num % 3 == 0);

assert_eq!(iter.next().unwrap(), &[10, 40]);
assert_eq!(iter.next().unwrap(), &[20]);
assert!(iter.next().is_none());

If the first element is matched, an empty slice will be the first item returned by the iterator. Similarly, if the last element in the slice is matched, an empty slice will be the last item returned by the iterator:

let slice = [10, 40, 33];
let mut iter = slice.split(|num| num % 3 == 0);

assert_eq!(iter.next().unwrap(), &[10, 40]);
assert_eq!(iter.next().unwrap(), &[]);
assert!(iter.next().is_none());

If two matched elements are directly adjacent, an empty slice will be present between them:

let slice = [10, 6, 33, 20];
let mut iter = slice.split(|num| num % 3 == 0);

assert_eq!(iter.next().unwrap(), &[10]);
assert_eq!(iter.next().unwrap(), &[]);
assert_eq!(iter.next().unwrap(), &[20]);
assert!(iter.next().is_none());
1.0.0 · Source

pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<'_, T, F>
where F: FnMut(&T) -> bool,

Returns an iterator over mutable subslices separated by elements that match pred。 此 matched element is not contained in the subslices.

§示例
let mut v = [10, 40, 30, 20, 60, 50];

for group in v.split_mut(|num| *num % 3 == 0) {
    group[0] = 1;
}
assert_eq!(v, [1, 40, 30, 1, 60, 1]);
1.51.0 · Source

pub fn split_inclusive<F>(&self, pred: F) -> SplitInclusive<'_, T, F>
where F: FnMut(&T) -> bool,

Returns an iterator over subslices separated by elements that match pred。 此 matched element is contained in the end of the previous subslice as 一个 terminator.

§示例
let slice = [10, 40, 33, 20];
let mut iter = slice.split_inclusive(|num| num % 3 == 0);

assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
assert_eq!(iter.next().unwrap(), &[20]);
assert!(iter.next().is_none());

If the last element of the slice is matched, that element will be considered the terminator of the preceding slice. That slice will be the last item returned by the iterator.

let slice = [3, 10, 40, 33];
let mut iter = slice.split_inclusive(|num| num % 3 == 0);

assert_eq!(iter.next().unwrap(), &[3]);
assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
assert!(iter.next().is_none());
1.51.0 · Source

pub fn split_inclusive_mut<F>(&mut self, pred: F) -> SplitInclusiveMut<'_, T, F>
where F: FnMut(&T) -> bool,

Returns an iterator over mutable subslices separated by elements that match pred。 此 matched element is contained in the previous subslice as 一个 terminator.

§示例
let mut v = [10, 40, 30, 20, 60, 50];

for group in v.split_inclusive_mut(|num| *num % 3 == 0) {
    let terminator_idx = group.len()-1;
    group[terminator_idx] = 1;
}
assert_eq!(v, [10, 40, 1, 20, 1, 1]);
1.27.0 · Source

pub fn rsplit<F>(&self, pred: F) -> RSplit<'_, T, F>
where F: FnMut(&T) -> bool,

Returns an iterator over subslices separated by elements that match pred, starting at the end of the slice 并 working backwards. 此 matched element is not contained in the subslices.

§示例
let slice = [11, 22, 33, 0, 44, 55];
let mut iter = slice.rsplit(|num| *num == 0);

assert_eq!(iter.next().unwrap(), &[44, 55]);
assert_eq!(iter.next().unwrap(), &[11, 22, 33]);
assert_eq!(iter.next(), None);

As with split(), if the first or last element is matched, an empty slice will be the first (or last) item returned by the iterator.

let v = &[0, 1, 1, 2, 3, 5, 8];
let mut it = v.rsplit(|n| *n % 2 == 0);
assert_eq!(it.next().unwrap(), &[]);
assert_eq!(it.next().unwrap(), &[3, 5]);
assert_eq!(it.next().unwrap(), &[1, 1]);
assert_eq!(it.next().unwrap(), &[]);
assert_eq!(it.next(), None);
1.27.0 · Source

pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<'_, T, F>
where F: FnMut(&T) -> bool,

Returns an iterator over mutable subslices separated by elements that match pred, starting at the end of the slice 并 working backwards. 此 matched element is not contained in the subslices.

§示例
let mut v = [100, 400, 300, 200, 600, 500];

let mut count = 0;
for group in v.rsplit_mut(|num| *num % 3 == 0) {
    count += 1;
    group[0] = count;
}
assert_eq!(v, [3, 400, 300, 2, 600, 1]);
1.0.0 · Source

pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<'_, T, F>
where F: FnMut(&T) -> bool,

Returns an iterator over subslices separated by elements that match pred, limited 到 returning at most n items. 此 matched element is not contained in the subslices.

此 last element returned, if any, will contain the remainder of the slice.

§示例

Print the slice split once by numbers divisible by 3 (i.e., [10, 40], [20, 60, 50]):

let v = [10, 40, 30, 20, 60, 50];

for group in v.splitn(2, |num| *num % 3 == 0) {
    println!("{group:?}");
}
1.0.0 · Source

pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<'_, T, F>
where F: FnMut(&T) -> bool,

Returns an iterator over mutable subslices separated by elements that match pred, limited 到 returning at most n items. 此 matched element is not contained in the subslices.

此 last element returned, if any, will contain the remainder of the slice.

§示例
let mut v = [10, 40, 30, 20, 60, 50];

for group in v.splitn_mut(2, |num| *num % 3 == 0) {
    group[0] = 1;
}
assert_eq!(v, [1, 40, 30, 1, 60, 50]);
1.0.0 · Source

pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<'_, T, F>
where F: FnMut(&T) -> bool,

Returns an iterator over subslices separated by elements that match pred limited 到 returning at most n items. This starts at the end of the slice 并 works backwards. 此 matched element is not contained in the subslices.

此 last element returned, if any, will contain the remainder of the slice.

§示例

Print the slice split once, starting 从 the end, by numbers divisible by 3 (i.e., [50], [10, 40, 30, 20]):

let v = [10, 40, 30, 20, 60, 50];

for group in v.rsplitn(2, |num| *num % 3 == 0) {
    println!("{group:?}");
}
1.0.0 · Source

pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<'_, T, F>
where F: FnMut(&T) -> bool,

Returns an iterator over subslices separated by elements that match pred limited 到 returning at most n items. This starts at the end of the slice 并 works backwards. 此 matched element is not contained in the subslices.

此 last element returned, if any, will contain the remainder of the slice.

§示例
let mut s = [10, 40, 30, 20, 60, 50];

for group in s.rsplitn_mut(2, |num| *num % 3 == 0) {
    group[0] = 1;
}
assert_eq!(s, [1, 40, 30, 20, 60, 1]);
Source

pub fn split_once<F>(&self, pred: F) -> Option<(&[T], &[T])>
where F: FnMut(&T) -> bool,

🔬This is a nightly-only experimental API. (slice_split_once)

Splits the slice on the first element that matches the specified predicate.

If any matching elements are present in the slice, returns the prefix before the match 并 suffix after. 此 matching element itself is not included. If no elements match, returns None

§示例
#![feature(slice_split_once)]
let s = [1, 2, 3, 2, 4];
assert_eq!(s.split_once(|&x| x == 2), Some((
    &[1][..],
    &[3, 2, 4][..]
)));
assert_eq!(s.split_once(|&x| x == 0), None);
Source

pub fn rsplit_once<F>(&self, pred: F) -> Option<(&[T], &[T])>
where F: FnMut(&T) -> bool,

🔬This is a nightly-only experimental API. (slice_split_once)

Splits the slice on the last element that matches the specified predicate.

If any matching elements are present in the slice, returns the prefix before the match 并 suffix after. 此 matching element itself is not included. If no elements match, returns None

§示例
#![feature(slice_split_once)]
let s = [1, 2, 3, 2, 4];
assert_eq!(s.rsplit_once(|&x| x == 2), Some((
    &[1, 2, 3][..],
    &[4][..]
)));
assert_eq!(s.rsplit_once(|&x| x == 0), None);
1.0.0 · Source

pub fn contains(&self, x: &T) -> bool
where T: PartialEq,

Returns true if the slice contains an element with the given value.

This operation is O(n)。

Note that if you have 一个 sorted slice, binary_search may be faster.

§示例
let v = [10, 40, 30];
assert!(v.contains(&30));
assert!(!v.contains(&50));

If you do not have a &T, but some other value that you can compare with one (for example, String implements PartialEq<str>), you can use iter().any:

let v = [String::from("hello"), String::from("world")]; // slice of `String`
assert!(v.iter().any(|e| e == "hello")); // search with `&str`
assert!(!v.iter().any(|e| e == "hi"));
1.0.0 · Source

pub fn starts_with(&self, needle: &[T]) -> bool
where T: PartialEq,

Returns true if needle 是 prefix of the slice 或 equal 到 the slice.

§示例
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:

let v = &[10, 40, 30];
assert!(v.starts_with(&[]));
let v: &[u8] = &[];
assert!(v.starts_with(&[]));
1.0.0 · Source

pub fn ends_with(&self, needle: &[T]) -> bool
where T: PartialEq,

Returns true if needle 是 suffix of the slice 或 equal 到 the slice.

§示例
let v = [10, 40, 30];
assert!(v.ends_with(&[30]));
assert!(v.ends_with(&[40, 30]));
assert!(v.ends_with(&v));
assert!(!v.ends_with(&[50]));
assert!(!v.ends_with(&[50, 30]));

Always returns true if needle is an empty slice:

let v = &[10, 40, 30];
assert!(v.ends_with(&[]));
let v: &[u8] = &[];
assert!(v.ends_with(&[]));
1.51.0 · Source

pub fn strip_prefix<P>(&self, prefix: &P) -> Option<&[T]>
where P: SlicePattern<Item = T> + ?Sized, T: PartialEq,

Returns 一个 subslice with the prefix removed.

If the slice starts with prefix, returns the subslice after the prefix, wrapped in Some。 If prefix is empty, simply returns the original slice. If prefix is equal 到 the original slice, returns an empty slice.

If the slice does not start with prefix, returns None

§示例
let v = &[10, 40, 30];
assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..]));
assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..]));
assert_eq!(v.strip_prefix(&[10, 40, 30]), Some(&[][..]));
assert_eq!(v.strip_prefix(&[50]), None);
assert_eq!(v.strip_prefix(&[10, 50]), None);

let prefix : &str = "he";
assert_eq!(b"hello".strip_prefix(prefix.as_bytes()),
           Some(b"llo".as_ref()));
1.51.0 · Source

pub fn strip_suffix<P>(&self, suffix: &P) -> Option<&[T]>
where P: SlicePattern<Item = T> + ?Sized, T: PartialEq,

Returns 一个 subslice with the suffix removed.

If the slice ends with suffix, returns the subslice before the suffix, wrapped in Some。 If suffix is empty, simply returns the original slice. If suffix is equal 到 the original slice, returns an empty slice.

If the slice does not end with suffix, returns None

§示例
let v = &[10, 40, 30];
assert_eq!(v.strip_suffix(&[30]), Some(&[10, 40][..]));
assert_eq!(v.strip_suffix(&[40, 30]), Some(&[10][..]));
assert_eq!(v.strip_suffix(&[10, 40, 30]), Some(&[][..]));
assert_eq!(v.strip_suffix(&[50]), None);
assert_eq!(v.strip_suffix(&[50, 30]), None);
Source

pub fn strip_circumfix<S, P>(&self, prefix: &P, suffix: &S) -> Option<&[T]>
where T: PartialEq, S: SlicePattern<Item = T> + ?Sized, P: SlicePattern<Item = T> + ?Sized,

🔬This is a nightly-only experimental API. (strip_circumfix)

Returns 一个 subslice with the prefix 并 suffix removed.

If the slice starts with prefix 并 ends with suffix, returns the subslice after the prefix 并 before the suffix, wrapped in Some

If the slice does not start with prefix 或 does not end with suffix, returns None

§示例
#![feature(strip_circumfix)]

let v = &[10, 50, 40, 30];
assert_eq!(v.strip_circumfix(&[10], &[30]), Some(&[50, 40][..]));
assert_eq!(v.strip_circumfix(&[10], &[40, 30]), Some(&[50][..]));
assert_eq!(v.strip_circumfix(&[10, 50], &[40, 30]), Some(&[][..]));
assert_eq!(v.strip_circumfix(&[50], &[30]), None);
assert_eq!(v.strip_circumfix(&[10], &[40]), None);
assert_eq!(v.strip_circumfix(&[], &[40, 30]), Some(&[10, 50][..]));
assert_eq!(v.strip_circumfix(&[10, 50], &[]), Some(&[40, 30][..]));
Source

pub fn trim_prefix<P>(&self, prefix: &P) -> &[T]
where P: SlicePattern<Item = T> + ?Sized, T: PartialEq,

🔬This is a nightly-only experimental API. (trim_prefix_suffix)

Returns 一个 subslice with the optional prefix removed.

If the slice starts with prefix, returns the subslice after the prefix. If prefix is empty 或 the slice does not start with prefix, simply returns the original slice. If prefix is equal 到 the original slice, returns an empty slice.

§示例
#![feature(trim_prefix_suffix)]

let v = &[10, 40, 30];

// Prefix present - removes it
assert_eq!(v.trim_prefix(&[10]), &[40, 30][..]);
assert_eq!(v.trim_prefix(&[10, 40]), &[30][..]);
assert_eq!(v.trim_prefix(&[10, 40, 30]), &[][..]);

// Prefix absent - returns original slice
assert_eq!(v.trim_prefix(&[50]), &[10, 40, 30][..]);
assert_eq!(v.trim_prefix(&[10, 50]), &[10, 40, 30][..]);

let prefix : &str = "he";
assert_eq!(b"hello".trim_prefix(prefix.as_bytes()), b"llo".as_ref());
Source

pub fn trim_suffix<P>(&self, suffix: &P) -> &[T]
where P: SlicePattern<Item = T> + ?Sized, T: PartialEq,

🔬This is a nightly-only experimental API. (trim_prefix_suffix)

Returns 一个 subslice with the optional suffix removed.

If the slice ends with suffix, returns the subslice before the suffix. If suffix is empty 或 the slice does not end with suffix, simply returns the original slice. If suffix is equal 到 the original slice, returns an empty slice.

§示例
#![feature(trim_prefix_suffix)]

let v = &[10, 40, 30];

// Suffix present - removes it
assert_eq!(v.trim_suffix(&[30]), &[10, 40][..]);
assert_eq!(v.trim_suffix(&[40, 30]), &[10][..]);
assert_eq!(v.trim_suffix(&[10, 40, 30]), &[][..]);

// Suffix absent - returns original slice
assert_eq!(v.trim_suffix(&[50]), &[10, 40, 30][..]);
assert_eq!(v.trim_suffix(&[50, 30]), &[10, 40, 30][..]);

Binary searches this slice 用于 一个 given element. If the slice is not sorted, the returned result is unspecified 并 meaningless.

If the value is found then Result::Ok is returned, containing the index of the matching element. If there are multiple matches, then any one of the matches could be returned. 此 index is chosen deterministically, but is subject 到 change in future versions of Rust. If the value is not found then Result::Err is returned, containing the index where 一个 matching element could be inserted while maintaining sorted order.

See also binary_search_by, binary_search_by_key, 并 partition_point

§示例

Looks up 一个 series of four elements. 此 first is found, with 一个 uniquely determined position; the second 并 third are not found; the fourth could match any position in [1, 4]

let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];

assert_eq!(s.binary_search(&13),  Ok(9));
assert_eq!(s.binary_search(&4),   Err(7));
assert_eq!(s.binary_search(&100), Err(13));
let r = s.binary_search(&1);
assert!(match r { Ok(1..=4) => true, _ => false, });

If you want to find that whole range of matching items, rather than an arbitrary matching one, that can be done using partition_point:

let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];

let low = s.partition_point(|x| x < &1);
assert_eq!(low, 1);
let high = s.partition_point(|x| x <= &1);
assert_eq!(high, 5);
let r = s.binary_search(&1);
assert!((low..high).contains(&r.unwrap()));

assert!(s[..low].iter().all(|&x| x < 1));
assert!(s[low..high].iter().all(|&x| x == 1));
assert!(s[high..].iter().all(|&x| x > 1));

// For something not found, the "range" of equal items is empty
assert_eq!(s.partition_point(|x| x < &11), 9);
assert_eq!(s.partition_point(|x| x <= &11), 9);
assert_eq!(s.binary_search(&11), Err(9));

If you want to insert an item to a sorted vector, while maintaining sort order, consider using partition_point:

let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
let num = 42;
let idx = s.partition_point(|&x| x <= num);
// If `num` is unique, `s.partition_point(|&x| x < num)` (with `<`) is equivalent to
// `s.binary_search(&num).unwrap_or_else(|x| x)`, but using `<=` will allow `insert`
// to shift less elements.
s.insert(idx, num);
assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
1.0.0 · Source

pub fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>
where F: FnMut(&'a T) -> Ordering,

Binary searches this slice with 一个 comparator function.

此 comparator function should return an order code that indicates whether its argument is Less, EqualGreater the desired target. If the slice is not sorted 或 if the comparator function does not implement an order consistent with the sort order of 底层 slice, the returned result is unspecified 并 meaningless.

If the value is found then Result::Ok is returned, containing the index of the matching element. If there are multiple matches, then any one of the matches could be returned. 此 index is chosen deterministically, but is subject 到 change in future versions of Rust. If the value is not found then Result::Err is returned, containing the index where 一个 matching element could be inserted while maintaining sorted order.

See also binary_search, binary_search_by_key, 并 partition_point

§示例

Looks up 一个 series of four elements. 此 first is found, with 一个 uniquely determined position; the second 并 third are not found; the fourth could match any position in [1, 4]

let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];

let seek = 13;
assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
let seek = 4;
assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
let seek = 100;
assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
let seek = 1;
let r = s.binary_search_by(|probe| probe.cmp(&seek));
assert!(match r { Ok(1..=4) => true, _ => false, });
1.10.0 · Source

pub fn binary_search_by_key<'a, B, F>( &'a self, b: &B, f: F, ) -> Result<usize, usize>
where F: FnMut(&'a T) -> B, B: Ord,

Binary searches this slice with 一个 key extraction function.

Assumes that the slice is sorted by the key, 用于 instance with sort_by_key using the same key extraction function. If the slice is not sorted by the key, the returned result is unspecified 并 meaningless.

If the value is found then Result::Ok is returned, containing the index of the matching element. If there are multiple matches, then any one of the matches could be returned. 此 index is chosen deterministically, but is subject 到 change in future versions of Rust. If the value is not found then Result::Err is returned, containing the index where 一个 matching element could be inserted while maintaining sorted order.

See also binary_search, binary_search_by, 并 partition_point

§示例

Looks up 一个 series of four elements in 一个 slice of pairs sorted by their second elements. 此 first is found, with 一个 uniquely determined position; the second 并 third are not found; the fourth could match any position in [1, 4]

let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
         (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
         (1, 21), (2, 34), (4, 55)];

assert_eq!(s.binary_search_by_key(&13, |&(a, b)| b),  Ok(9));
assert_eq!(s.binary_search_by_key(&4, |&(a, b)| b),   Err(7));
assert_eq!(s.binary_search_by_key(&100, |&(a, b)| b), Err(13));
let r = s.binary_search_by_key(&1, |&(a, b)| b);
assert!(match r { Ok(1..=4) => true, _ => false, });
1.20.0 · Source

pub fn sort_unstable(&mut self)
where T: Ord,

Sorts the slice in ascending order without preserving the initial order of equal elements.

This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not allocate), 并 O(n * log(n)) worst-case.

If the implementation of Ord 用于 T does not implement 一个 total order, 函数 may panic; even if 函数 exits normally, the resulting order of elements in the slice is unspecified. See also the note on panicking below.

For example |一个, b| (一个 - b).cmp(一个) 是 comparison function , neither transitive nor reflexive nor total, 一个 < b < c < 一个 with 一个 = 1, b = 2, c = 3。 For more information 并 examples see the Ord documentation.

All original elements will remain in the slice 并 any possible modifications via interior mutability are observed in 输入. Same is true if the implementation of Ord 用于 T panics.

Sorting types that only implement PartialOrd such as f32f64 require additional precautions. For example, f32::NAN != f32::NAN, which doesn’t fulfill the reflexivity requirement of Ord。 By using an alternative comparison function with slice::sort_unstable_by such as f32::total_cmpf64::total_cmp that defines 一个 total order users can sort slices containing floating-point values. Alternatively, if all values in the slice are guaranteed 到 be in 一个 subset 用于 which PartialOrd::partial_cmp forms 一个 total order, it’s possible 到 sort the slice with sort_unstable_by(|一个, b| 一个.partial_cmp(b).unwrap())

§Current implementation

此 current implementation is based on ipnsort by Lukas Bergdoll 并 Orson Peters, which combines the fast average case of quicksort with the fast worst case of heapsort, achieving linear time on fully sorted 并 reversed inputs. On inputs with k distinct elements, the expected time 到 sort 数据 is O(n * log(k))。

It is typically faster than stable sorting, except in 一个 few special cases, e.g., when the slice is partially sorted.

§Panics

May panic if the implementation of Ord 用于 T does not implement 一个 total order, 或 if the Ord implementation panics.

§示例
let mut v = [4, -5, 1, -3, 2];

v.sort_unstable();
assert_eq!(v, [-5, -3, 1, 2, 4]);
1.20.0 · Source

pub fn sort_unstable_by<F>(&mut self, compare: F)
where F: FnMut(&T, &T) -> Ordering,

Sorts the slice in ascending order with 一个 comparison function, without preserving the initial order of equal elements.

This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not allocate), 并 O(n * log(n)) worst-case.

If the comparison function compare does not implement 一个 total order, 函数 may panic; even if 函数 exits normally, the resulting order of elements in the slice is unspecified. See also the note on panicking below.

For example |一个, b| (一个 - b).cmp(一个) 是 comparison function , neither transitive nor reflexive nor total, 一个 < b < c < 一个 with 一个 = 1, b = 2, c = 3。 For more information 并 examples see the Ord documentation.

All original elements will remain in the slice 并 any possible modifications via interior mutability are observed in 输入. Same is true if compare panics.

§Current implementation

此 current implementation is based on ipnsort by Lukas Bergdoll 并 Orson Peters, which combines the fast average case of quicksort with the fast worst case of heapsort, achieving linear time on fully sorted 并 reversed inputs. On inputs with k distinct elements, the expected time 到 sort 数据 is O(n * log(k))。

It is typically faster than stable sorting, except in 一个 few special cases, e.g., when the slice is partially sorted.

§Panics

May panic if the compare does not implement 一个 total order, 或 if the compare itself panics.

§示例
let mut v = [4, -5, 1, -3, 2];
v.sort_unstable_by(|a, b| a.cmp(b));
assert_eq!(v, [-5, -3, 1, 2, 4]);

// reverse sorting
v.sort_unstable_by(|a, b| b.cmp(a));
assert_eq!(v, [4, 2, 1, -3, -5]);
1.20.0 · Source

pub fn sort_unstable_by_key<K, F>(&mut self, f: F)
where F: FnMut(&T) -> K, K: Ord,

Sorts the slice in ascending order with 一个 key extraction function, without preserving the initial order of equal elements.

This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not allocate), 并 O(n * log(n)) worst-case.

If the implementation of Ord 用于 K does not implement 一个 total order, 函数 may panic; even if 函数 exits normally, the resulting order of elements in the slice is unspecified. See also the note on panicking below.

For example |一个, b| (一个 - b).cmp(一个) 是 comparison function , neither transitive nor reflexive nor total, 一个 < b < c < 一个 with 一个 = 1, b = 2, c = 3。 For more information 并 examples see the Ord documentation.

All original elements will remain in the slice 并 any possible modifications via interior mutability are observed in 输入. Same is true if the implementation of Ord 用于 K panics.

§Current implementation

此 current implementation is based on ipnsort by Lukas Bergdoll 并 Orson Peters, which combines the fast average case of quicksort with the fast worst case of heapsort, achieving linear time on fully sorted 并 reversed inputs. On inputs with k distinct elements, the expected time 到 sort 数据 is O(n * log(k))。

It is typically faster than stable sorting, except in 一个 few special cases, e.g., when the slice is partially sorted.

§Panics

May panic if the implementation of Ord 用于 K does not implement 一个 total order, 或 if the Ord implementation panics.

§示例
let mut v = [4i32, -5, 1, -3, 2];

v.sort_unstable_by_key(|k| k.abs());
assert_eq!(v, [1, 2, -3, 4, -5]);
Source

pub fn partial_sort_unstable<R>(&mut self, range: R)
where T: Ord, R: RangeBounds<usize>,

🔬This is a nightly-only experimental API. (slice_partial_sort_unstable)

Partially sorts the slice in ascending order without preserving the initial order of equal elements.

Upon completion, 用于 the specified range start..end, it’s guaranteed that:

  1. Every element in self[..start] is smaller than or equal to
  2. Every element in self[start..end], which is sorted, and smaller than or equal to
  3. Every element in self[end..].

This partial sort is unstable, meaning it may reorder equal elements in the specified range. It may reorder elements outside the specified range as well, but the guarantees above still hold.

This partial sort is in-place (i.e., does not allocate), 并 O(n + k * log(k)) worst-case, where n 是 length of the slice 并 k 是 length of the specified range.

,请参见 documentation of sort_unstable 用于 implementation notes.

§Panics

May panic if the implementation of Ord 用于 T does not implement 一个 total order, 或 if the Ord implementation panics, 或 if the specified range is out of bounds.

§示例
#![feature(slice_partial_sort_unstable)]

let mut v = [4, -5, 1, -3, 2];

// empty range at the beginning, nothing changed
v.partial_sort_unstable(0..0);
assert_eq!(v, [4, -5, 1, -3, 2]);

// empty range in the middle, partitioning the slice
v.partial_sort_unstable(2..2);
for i in 0..2 {
   assert!(v[i] <= v[2]);
}
for i in 3..v.len() {
  assert!(v[2] <= v[i]);
}

// single element range, same as select_nth_unstable
v.partial_sort_unstable(2..3);
for i in 0..2 {
   assert!(v[i] <= v[2]);
}
for i in 3..v.len() {
  assert!(v[2] <= v[i]);
}

// partial sort a subrange
v.partial_sort_unstable(1..4);
assert_eq!(&v[1..4], [-3, 1, 2]);

// partial sort the whole range, same as sort_unstable
v.partial_sort_unstable(..);
assert_eq!(v, [-5, -3, 1, 2, 4]);
Source

pub fn partial_sort_unstable_by<F, R>(&mut self, range: R, compare: F)
where F: FnMut(&T, &T) -> Ordering, R: RangeBounds<usize>,

🔬This is a nightly-only experimental API. (slice_partial_sort_unstable)

Partially sorts the slice in ascending order with 一个 comparison function, without preserving the initial order of equal elements.

Upon completion, 用于 the specified range start..end, it’s guaranteed that:

  1. Every element in self[..start] is smaller than or equal to
  2. Every element in self[start..end], which is sorted, and smaller than or equal to
  3. Every element in self[end..].

This partial sort is unstable, meaning it may reorder equal elements in the specified range. It may reorder elements outside the specified range as well, but the guarantees above still hold.

This partial sort is in-place (i.e., does not allocate), 并 O(n + k * log(k)) worst-case, where n 是 length of the slice 并 k 是 length of the specified range.

,请参见 documentation of sort_unstable_by 用于 implementation notes.

§Panics

May panic if the compare does not implement 一个 total order, 或 if the compare itself panics, 或 if the specified range is out of bounds.

§示例
#![feature(slice_partial_sort_unstable)]

let mut v = [4, -5, 1, -3, 2];

// empty range at the beginning, nothing changed
v.partial_sort_unstable_by(0..0, |a, b| b.cmp(a));
assert_eq!(v, [4, -5, 1, -3, 2]);

// empty range in the middle, partitioning the slice
v.partial_sort_unstable_by(2..2, |a, b| b.cmp(a));
for i in 0..2 {
   assert!(v[i] >= v[2]);
}
for i in 3..v.len() {
  assert!(v[2] >= v[i]);
}

// single element range, same as select_nth_unstable
v.partial_sort_unstable_by(2..3, |a, b| b.cmp(a));
for i in 0..2 {
   assert!(v[i] >= v[2]);
}
for i in 3..v.len() {
  assert!(v[2] >= v[i]);
}

// partial sort a subrange
v.partial_sort_unstable_by(1..4, |a, b| b.cmp(a));
assert_eq!(&v[1..4], [2, 1, -3]);

// partial sort the whole range, same as sort_unstable
v.partial_sort_unstable_by(.., |a, b| b.cmp(a));
assert_eq!(v, [4, 2, 1, -3, -5]);
Source

pub fn partial_sort_unstable_by_key<K, F, R>(&mut self, range: R, f: F)
where F: FnMut(&T) -> K, K: Ord, R: RangeBounds<usize>,

🔬This is a nightly-only experimental API. (slice_partial_sort_unstable)

Partially sorts the slice in ascending order with 一个 key extraction function, without preserving the initial order of equal elements.

Upon completion, 用于 the specified range start..end, it’s guaranteed that:

  1. Every element in self[..start] is smaller than or equal to
  2. Every element in self[start..end], which is sorted, and smaller than or equal to
  3. Every element in self[end..].

This partial sort is unstable, meaning it may reorder equal elements in the specified range. It may reorder elements outside the specified range as well, but the guarantees above still hold.

This partial sort is in-place (i.e., does not allocate), 并 O(n + k * log(k)) worst-case, where n 是 length of the slice 并 k 是 length of the specified range.

,请参见 documentation of sort_unstable_by_key 用于 implementation notes.

§Panics

May panic if the implementation of Ord 用于 K does not implement 一个 total order, 或 if the Ord implementation panics, 或 if the specified range is out of bounds.

§示例
#![feature(slice_partial_sort_unstable)]

let mut v = [4i32, -5, 1, -3, 2];

// empty range at the beginning, nothing changed
v.partial_sort_unstable_by_key(0..0, |k| k.abs());
assert_eq!(v, [4, -5, 1, -3, 2]);

// empty range in the middle, partitioning the slice
v.partial_sort_unstable_by_key(2..2, |k| k.abs());
for i in 0..2 {
   assert!(v[i].abs() <= v[2].abs());
}
for i in 3..v.len() {
  assert!(v[2].abs() <= v[i].abs());
}

// single element range, same as select_nth_unstable
v.partial_sort_unstable_by_key(2..3, |k| k.abs());
for i in 0..2 {
   assert!(v[i].abs() <= v[2].abs());
}
for i in 3..v.len() {
  assert!(v[2].abs() <= v[i].abs());
}

// partial sort a subrange
v.partial_sort_unstable_by_key(1..4, |k| k.abs());
assert_eq!(&v[1..4], [2, -3, 4]);

// partial sort the whole range, same as sort_unstable
v.partial_sort_unstable_by_key(.., |k| k.abs());
assert_eq!(v, [1, 2, -3, 4, -5]);
1.49.0 · Source

pub fn select_nth_unstable( &mut self, index: usize, ) -> (&mut [T], &mut T, &mut [T])
where T: Ord,

Reorders the slice such that the element at index is at 一个 sort-order position. All elements before index<= 到 this value, 并 all elements after , >= 到 it.

This reordering is unstable (i.e. any element that compares equal 到 the nth element may end up at that position), in-place (i.e. does not allocate), 并 runs in O(n) time. This function 也 known as “kth element” in other libraries.

Returns 一个 triple that partitions the reordered slice:

  • 此 unsorted subslice before index, whose elements all satisfy x <= self[index]

  • 此 element at index

  • 此 unsorted subslice after index, whose elements all satisfy x >= self[index]

§Current implementation

此 current 算法 是 introselect implementation based on ipnsort by Lukas Bergdoll 并 Orson Peters, which 也 the basis 用于 sort_unstable。 此 fallback 算法 is Median of Medians using Tukey’s Ninther 用于 pivot selection, which guarantees linear runtime 用于 all inputs.

§Panics

Panics when index >= len(), 并 so always panics on empty slices.

May panic if the implementation of Ord 用于 T does not implement 一个 total order

§示例
let mut v = [-5i32, 4, 2, -3, 1];

// Find the items `<=` to the median, the median itself, and the items `>=` to it.
let (lesser, median, greater) = v.select_nth_unstable(2);

assert!(lesser == [-3, -5] || lesser == [-5, -3]);
assert_eq!(median, &mut 1);
assert!(greater == [4, 2] || greater == [2, 4]);

// We are only guaranteed the slice will be one of the following, based on the way we sort
// about the specified index.
assert!(v == [-3, -5, 1, 2, 4] ||
        v == [-5, -3, 1, 2, 4] ||
        v == [-3, -5, 1, 4, 2] ||
        v == [-5, -3, 1, 4, 2]);
1.49.0 · Source

pub fn select_nth_unstable_by<F>( &mut self, index: usize, compare: F, ) -> (&mut [T], &mut T, &mut [T])
where F: FnMut(&T, &T) -> Ordering,

Reorders the slice with 一个 comparator function such that the element at index is at 一个 sort-order position. All elements before index<= 到 this value, 并 all elements after , >= 到 it, according 到 the comparator function.

This reordering is unstable (i.e. any element that compares equal 到 the nth element may end up at that position), in-place (i.e. does not allocate), 并 runs in O(n) time. This function 也 known as “kth element” in other libraries.

Returns 一个 triple partitioning the reordered slice:

  • 此 unsorted subslice before index, whose elements all satisfy compare(x, self[index]).is_le()

  • 此 element at index

  • 此 unsorted subslice after index, whose elements all satisfy compare(x, self[index]).is_ge()

§Current implementation

此 current 算法 是 introselect implementation based on ipnsort by Lukas Bergdoll 并 Orson Peters, which 也 the basis 用于 sort_unstable。 此 fallback 算法 is Median of Medians using Tukey’s Ninther 用于 pivot selection, which guarantees linear runtime 用于 all inputs.

§Panics

Panics when index >= len(), 并 so always panics on empty slices.

May panic if compare does not implement 一个 total order

§示例
let mut v = [-5i32, 4, 2, -3, 1];

// Find the items `>=` to the median, the median itself, and the items `<=` to it, by using
// a reversed comparator.
let (before, median, after) = v.select_nth_unstable_by(2, |a, b| b.cmp(a));

assert!(before == [4, 2] || before == [2, 4]);
assert_eq!(median, &mut 1);
assert!(after == [-3, -5] || after == [-5, -3]);

// We are only guaranteed the slice will be one of the following, based on the way we sort
// about the specified index.
assert!(v == [2, 4, 1, -5, -3] ||
        v == [2, 4, 1, -3, -5] ||
        v == [4, 2, 1, -5, -3] ||
        v == [4, 2, 1, -3, -5]);
1.49.0 · Source

pub fn select_nth_unstable_by_key<K, F>( &mut self, index: usize, f: F, ) -> (&mut [T], &mut T, &mut [T])
where F: FnMut(&T) -> K, K: Ord,

Reorders the slice with 一个 key extraction function such that the element at index is at 一个 sort-order position. All elements before index will have keys <= 到 the key at index, 并 all elements after will have keys >= 到 it.

This reordering is unstable (i.e. any element that compares equal 到 the nth element may end up at that position), in-place (i.e. does not allocate), 并 runs in O(n) time. This function 也 known as “kth element” in other libraries.

Returns 一个 triple partitioning the reordered slice:

  • 此 unsorted subslice before index, whose elements all satisfy f(x) <= f(self[index])

  • 此 element at index

  • 此 unsorted subslice after index, whose elements all satisfy f(x) >= f(self[index])

§Current implementation

此 current 算法 是 introselect implementation based on ipnsort by Lukas Bergdoll 并 Orson Peters, which 也 the basis 用于 sort_unstable。 此 fallback 算法 is Median of Medians using Tukey’s Ninther 用于 pivot selection, which guarantees linear runtime 用于 all inputs.

§Panics

Panics when index >= len(), meaning it always panics on empty slices.

May panic if K: Ord does not implement 一个 total order.

§示例
let mut v = [-5i32, 4, 1, -3, 2];

// Find the items `<=` to the absolute median, the absolute median itself, and the items
// `>=` to it.
let (lesser, median, greater) = v.select_nth_unstable_by_key(2, |a| a.abs());

assert!(lesser == [1, 2] || lesser == [2, 1]);
assert_eq!(median, &mut -3);
assert!(greater == [4, -5] || greater == [-5, 4]);

// We are only guaranteed the slice will be one of the following, based on the way we sort
// about the specified index.
assert!(v == [1, 2, -3, 4, -5] ||
        v == [1, 2, -3, -5, 4] ||
        v == [2, 1, -3, 4, -5] ||
        v == [2, 1, -3, -5, 4]);
Source

pub fn partition_dedup(&mut self) -> (&mut [T], &mut [T])
where T: PartialEq,

🔬This is a nightly-only experimental API. (slice_partition_dedup)

Moves all consecutive repeated elements 到 the end of the slice according 到 the PartialEq trait implementation.

Returns two slices. 此 first contains no consecutive repeated elements. 此 second contains all the duplicates in no specified order.

If the slice is sorted, the first returned slice contains no duplicates.

§示例
#![feature(slice_partition_dedup)]

let mut slice = [1, 2, 2, 3, 3, 2, 1, 1];

let (dedup, duplicates) = slice.partition_dedup();

assert_eq!(dedup, [1, 2, 3, 2, 1]);
assert_eq!(duplicates, [2, 3, 1]);
Source

pub fn partition_dedup_by<F>(&mut self, same_bucket: F) -> (&mut [T], &mut [T])
where F: FnMut(&mut T, &mut T) -> bool,

🔬This is a nightly-only experimental API. (slice_partition_dedup)

Moves all but the first of consecutive elements 到 the end of the slice satisfying 一个 given equality relation.

Returns two slices. 此 first contains no consecutive repeated elements. 此 second contains all the duplicates in no specified order.

same_bucket function is passed references 到 two elements 从 the slice 并 must determine if the elements compare equal. 此 elements are passed in opposite order 从 their order in the slice, so if same_bucket(一个, b) returns true, 一个 is moved at the end of the slice.

If the slice is sorted, the first returned slice contains no duplicates.

§示例
#![feature(slice_partition_dedup)]

let mut slice = ["foo", "Foo", "BAZ", "Bar", "bar", "baz", "BAZ"];

let (dedup, duplicates) = slice.partition_dedup_by(|a, b| a.eq_ignore_ascii_case(b));

assert_eq!(dedup, ["foo", "BAZ", "Bar", "baz"]);
assert_eq!(duplicates, ["bar", "Foo", "BAZ"]);
Source

pub fn partition_dedup_by_key<K, F>(&mut self, key: F) -> (&mut [T], &mut [T])
where F: FnMut(&mut T) -> K, K: PartialEq,

🔬This is a nightly-only experimental API. (slice_partition_dedup)

Moves all but the first of consecutive elements 到 the end of the slice that resolve 到 the same key.

Returns two slices. 此 first contains no consecutive repeated elements. 此 second contains all the duplicates in no specified order.

If the slice is sorted, the first returned slice contains no duplicates.

§示例
#![feature(slice_partition_dedup)]

let mut slice = [10, 20, 21, 30, 30, 20, 11, 13];

let (dedup, duplicates) = slice.partition_dedup_by_key(|i| *i / 10);

assert_eq!(dedup, [10, 20, 30, 20, 11]);
assert_eq!(duplicates, [21, 30, 13]);
1.26.0 · Source

pub fn rotate_left(&mut self, mid: usize)

Rotates the slice in-place such that the first mid elements of the slice move 到 the end while the last self.len() - mid elements move 到 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 并 是 no-op rotation.

§Complexity

Takes linear (in self.len()) time.

§示例
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:

let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
a[1..5].rotate_left(1);
assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);
1.26.0 · Source

pub fn rotate_right(&mut self, k: usize)

Rotates the slice in-place such that the first self.len() - k elements of the slice move 到 the end while the last k elements move 到 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 并 是 no-op rotation.

§Complexity

Takes linear (in self.len()) time.

§示例
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:

let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
a[1..5].rotate_right(1);
assert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']);
Source

pub fn shift_left<const N: usize>(&mut self, inserted: [T; N]) -> [T; N]

🔬This is a nightly-only experimental API. (slice_shift)

Moves the elements of this slice N places 到 the left, returning the ones that “fall off” the front, 并 putting inserted at the end.

Equivalently, you can think of concatenating selfinserted into one long sequence, then returning the left-most N items 并 the rest into self:

          self (before)    inserted
          vvvvvvvvvvvvvvv  vvv
          [1, 2, 3, 4, 5]  [9]
       ↙   ↙  ↙  ↙  ↙   ↙
     [1]  [2, 3, 4, 5, 9]
     ^^^  ^^^^^^^^^^^^^^^
returned  self (after)

See also Self::shift_right and compare Self::rotate_left

§示例
#![feature(slice_shift)]

// Same as the diagram above
let mut a = [1, 2, 3, 4, 5];
let inserted = [9];
let returned = a.shift_left(inserted);
assert_eq!(returned, [1]);
assert_eq!(a, [2, 3, 4, 5, 9]);

// You can shift multiple items at a time
let mut a = *b"Hello world";
assert_eq!(a.shift_left(*b" peace"), *b"Hello ");
assert_eq!(a, *b"world peace");

// The name comes from this operation's similarity to bitshifts
let mut a: u8 = 0b10010110;
a <<= 3;
assert_eq!(a, 0b10110000_u8);
let mut a: [_; 8] = [1, 0, 0, 1, 0, 1, 1, 0];
a.shift_left([0; 3]);
assert_eq!(a, [1, 0, 1, 1, 0, 0, 0, 0]);

// Remember you can sub-slice to affect less that the whole slice.
// For example, this is similar to `.remove(1)` + `.insert(4, 'Z')`
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
assert_eq!(a[1..=4].shift_left(['Z']), ['b']);
assert_eq!(a, ['a', 'c', 'd', 'e', 'Z', 'f']);

// If the size matches it's equivalent to `mem::replace`
let mut a = [1, 2, 3];
assert_eq!(a.shift_left([7, 8, 9]), [1, 2, 3]);
assert_eq!(a, [7, 8, 9]);

// Some of the "inserted" elements end up returned if the slice is too short
let mut a = [];
assert_eq!(a.shift_left([1, 2, 3]), [1, 2, 3]);
let mut a = [9];
assert_eq!(a.shift_left([1, 2, 3]), [9, 1, 2]);
assert_eq!(a, [3]);
Source

pub fn shift_right<const N: usize>(&mut self, inserted: [T; N]) -> [T; N]

🔬This is a nightly-only experimental API. (slice_shift)

Moves the elements of this slice N places 到 the right, returning the ones that “fall off” the back, 并 putting inserted at the beginning.

Equivalently, you can think of concatenating insertedself into one long sequence, then returning the right-most N items 并 the rest into self:

inserted  self (before)
     vvv  vvvvvvvvvvvvvvv
     [0]  [5, 6, 7, 8, 9]
       ↘   ↘  ↘  ↘  ↘   ↘
          [0, 5, 6, 7, 8]  [9]
          ^^^^^^^^^^^^^^^  ^^^
          self (after)     returned

See also Self::shift_left and compare Self::rotate_right

§示例
#![feature(slice_shift)]

// Same as the diagram above
let mut a = [5, 6, 7, 8, 9];
let inserted = [0];
let returned = a.shift_right(inserted);
assert_eq!(returned, [9]);
assert_eq!(a, [0, 5, 6, 7, 8]);

// The name comes from this operation's similarity to bitshifts
let mut a: u8 = 0b10010110;
a >>= 3;
assert_eq!(a, 0b00010010_u8);
let mut a: [_; 8] = [1, 0, 0, 1, 0, 1, 1, 0];
a.shift_right([0; 3]);
assert_eq!(a, [0, 0, 0, 1, 0, 0, 1, 0]);

// Remember you can sub-slice to affect less that the whole slice.
// For example, this is similar to `.remove(4)` + `.insert(1, 'Z')`
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
assert_eq!(a[1..=4].shift_right(['Z']), ['e']);
assert_eq!(a, ['a', 'Z', 'b', 'c', 'd', 'f']);

// If the size matches it's equivalent to `mem::replace`
let mut a = [1, 2, 3];
assert_eq!(a.shift_right([7, 8, 9]), [1, 2, 3]);
assert_eq!(a, [7, 8, 9]);

// Some of the "inserted" elements end up returned if the slice is too short
let mut a = [];
assert_eq!(a.shift_right([1, 2, 3]), [1, 2, 3]);
let mut a = [9];
assert_eq!(a.shift_right([1, 2, 3]), [2, 3, 9]);
assert_eq!(a, [1]);
1.50.0 · Source

pub fn fill(&mut self, value: T)
where T: Clone,

Fills self with elements by cloning value

§示例
let mut buf = vec![0; 10];
buf.fill(1);
assert_eq!(buf, vec![1; 10]);
1.51.0 · Source

pub fn fill_with<F>(&mut self, f: F)
where F: FnMut() -> T,

Fills self with elements returned by calling 一个 closure repeatedly.

This method uses 一个 closure 到 create new values. If you’d rather Clone 一个 given value, use fill。 If you want 到 use the Default trait 到 generate values, you can pass Default::default as the argument.

§示例
let mut buf = vec![1; 10];
buf.fill_with(Default::default);
assert_eq!(buf, vec![0; 10]);
1.7.0 · Source

pub fn clone_from_slice(&mut self, src: &[T])
where T: Clone,

Copies the elements 从 src into self

此 length of src must be the same as self

§Panics

This function will panic if the two slices have different lengths.

§示例

Cloning two elements 从 一个 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:

let mut slice = [1, 2, 3, 4, 5];

slice[..2].clone_from_slice(&slice[3..]); // compile fail!

To work around this, we can use split_at_mut to create two distinct sub-slices 从 a slice:

let mut slice = [1, 2, 3, 4, 5];

{
    let (left, right) = slice.split_at_mut(2);
    left.clone_from_slice(&right[1..]);
}

assert_eq!(slice, [4, 5, 3, 4, 5]);
1.9.0 · Source

pub fn copy_from_slice(&mut self, src: &[T])
where T: Copy,

Copies all elements 从 src into self, using 一个 memcpy.

此 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.

§示例

Copying two elements 从 一个 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:

let mut slice = [1, 2, 3, 4, 5];

slice[..2].copy_from_slice(&slice[3..]); // compile fail!

To work around this, we can use split_at_mut to create two distinct sub-slices 从 a slice:

let mut slice = [1, 2, 3, 4, 5];

{
    let (left, right) = slice.split_at_mut(2);
    left.copy_from_slice(&right[1..]);
}

assert_eq!(slice, [4, 5, 3, 4, 5]);
1.37.0 · Source

pub fn copy_within<R>(&mut self, src: R, dest: usize)
where R: RangeBounds<usize>, T: Copy,

Copies elements 从 one part of the slice 到 another part of itself, using 一个 memmove.

src 是 range within self 到 copy 从。 dest 是 starting index of the range within self 到 copy 到, which will have the same length as src。 此 two ranges may overlap. 此 ends of the two ranges must be less than 或 equal 到 self.len()

§Panics

This function will panic if either range exceeds the end of the slice, 或 if the end of src is before the start.

§示例

Copying four bytes within 一个 slice:

let mut bytes = *b"Hello, World!";

bytes.copy_within(1..5, 8);

assert_eq!(&bytes, b"Hello, Wello!");
1.27.0 · Source

pub fn swap_with_slice(&mut self, other: &mut [T])

Swaps all elements in self with those in other

此 length of other must be the same as self

§Panics

This function will panic if the two slices have different lengths.

§Example

Swapping two elements across slices:

let mut slice1 = [0, 0];
let mut slice2 = [1, 2, 3, 4];

slice1.swap_with_slice(&mut slice2[2..]);

assert_eq!(slice1, [3, 4]);
assert_eq!(slice2, [1, 2, 0, 0]);

Rust enforces that there can only be one mutable reference to a particular piece of data in a particular scope. Because of this, attempting to use swap_with_slice on a single slice will result in a compile failure:

let mut slice = [1, 2, 3, 4, 5];
slice[..2].swap_with_slice(&mut slice[3..]); // compile fail!

To work around this, we can use split_at_mut to create two distinct mutable sub-slices 从 a slice:

let mut slice = [1, 2, 3, 4, 5];

{
    let (left, right) = slice.split_at_mut(2);
    left.swap_with_slice(&mut right[1..]);
}

assert_eq!(slice, [4, 5, 3, 1, 2]);
1.30.0 · Source

pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T])

Transmutes the slice 到 一个 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 新 type, 并 the suffix slice. 此 middle part , as big as possible under the given alignment constraint 并 element size.

This method has no purpose when either input element T 或 output element U are zero-sized 并 将返回 the original slice without splitting anything.

§Safety

This method is essentially 一个 transmute with respect 到 the elements in the returned middle slice, so all the usual caveats pertaining 到 transmute::<T, U> also apply here.

§示例

Basic usage:

unsafe {
    let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
    let (prefix, shorts, suffix) = bytes.align_to::<u16>();
    // less_efficient_algorithm_for_bytes(prefix);
    // more_efficient_algorithm_for_aligned_shorts(shorts);
    // less_efficient_algorithm_for_bytes(suffix);
}
1.30.0 · Source

pub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T])

Transmutes the mutable slice 到 一个 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 新 type, 并 the suffix slice. 此 middle part , as big as possible under the given alignment constraint 并 element size.

This method has no purpose when either input element T 或 output element U are zero-sized 并 将返回 the original slice without splitting anything.

§Safety

This method is essentially 一个 transmute with respect 到 the elements in the returned middle slice, so all the usual caveats pertaining 到 transmute::<T, U> also apply here.

§示例

Basic usage:

unsafe {
    let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
    let (prefix, shorts, suffix) = bytes.align_to_mut::<u16>();
    // less_efficient_algorithm_for_bytes(prefix);
    // more_efficient_algorithm_for_aligned_shorts(shorts);
    // less_efficient_algorithm_for_bytes(suffix);
}
Source

pub fn as_simd<const LANES: usize>(&self) -> (&[T], &[Simd<T, LANES>], &[T])
where Simd<T, LANES>: AsRef<[T; LANES]>, T: SimdElement,

🔬This is a nightly-only experimental API. (portable_simd)

Splits 一个 slice into 一个 prefix, 一个 middle of aligned SIMD types, 并 一个 suffix.

This 是 safe wrapper around slice::align_to, so inherits the same guarantees as that method.

§Panics

This will panic if the size of the SIMD type is different 从 LANES times that of the scalar.

At the time of writing, the trait restrictions on Simd<T, LANES> keeps that 从 ever happening, as only power-of-two numbers of lanes are supported. It’s possible that, in the future, those restrictions might be lifted in 一个 way that would make it possible 到 see panics 从 this method 用于 something like LANES == 3

§示例
#![feature(portable_simd)]
use core::simd::prelude::*;

let short = &[1, 2, 3];
let (prefix, middle, suffix) = short.as_simd::<4>();
assert_eq!(middle, []); // Not enough elements for anything in the middle

// They might be split in any possible way between prefix and suffix
let it = prefix.iter().chain(suffix).copied();
assert_eq!(it.collect::<Vec<_>>(), vec![1, 2, 3]);

fn basic_simd_sum(x: &[f32]) -> f32 {
    use std::ops::Add;
    let (prefix, middle, suffix) = x.as_simd();
    let sums = f32x4::from_array([
        prefix.iter().copied().sum(),
        0.0,
        0.0,
        suffix.iter().copied().sum(),
    ]);
    let sums = middle.iter().copied().fold(sums, f32x4::add);
    sums.reduce_sum()
}

let numbers: Vec<f32> = (1..101).map(|x| x as _).collect();
assert_eq!(basic_simd_sum(&numbers[1..99]), 4949.0);
Source

pub fn as_simd_mut<const LANES: usize>( &mut self, ) -> (&mut [T], &mut [Simd<T, LANES>], &mut [T])
where Simd<T, LANES>: AsMut<[T; LANES]>, T: SimdElement,

🔬This is a nightly-only experimental API. (portable_simd)

Splits 一个 mutable slice into 一个 mutable prefix, 一个 middle of aligned SIMD types, 并 一个 mutable suffix.

This 是 safe wrapper around slice::align_to_mut, so inherits the same guarantees as that method.

This 是 mutable version of slice::as_simd; see that 用于 examples.

§Panics

This will panic if the size of the SIMD type is different 从 LANES times that of the scalar.

At the time of writing, the trait restrictions on Simd<T, LANES> keeps that 从 ever happening, as only power-of-two numbers of lanes are supported. It’s possible that, in the future, those restrictions might be lifted in 一个 way that would make it possible 到 see panics 从 this method 用于 something like LANES == 3

1.82.0 · Source

pub fn is_sorted(&self) -> bool
where T: PartialOrd,

Checks if the elements of this slice are sorted.

That is, 用于 each element 一个 并 its following element b, 一个 <= b must hold. If the slice yields exactly zero 或 one element, true is returned.

Note that if Self::Item is only PartialOrd, but not Ord, the above definition implies that 此函数 returns false if any two consecutive items are not comparable.

§示例
let empty: [i32; 0] = [];

assert!([1, 2, 2, 9].is_sorted());
assert!(![1, 3, 2, 4].is_sorted());
assert!([0].is_sorted());
assert!(empty.is_sorted());
assert!(![0.0, 1.0, f32::NAN].is_sorted());
1.82.0 · Source

pub fn is_sorted_by<'a, F>(&'a self, compare: F) -> bool
where F: FnMut(&'a T, &'a T) -> bool,

Checks if the elements of this slice are sorted using the given comparator function.

Instead of using PartialOrd::partial_cmp, 此函数 uses the given compare function 到 determine whether two elements are 到 be considered in sorted order.

§示例
assert!([1, 2, 2, 9].is_sorted_by(|a, b| a <= b));
assert!(![1, 2, 2, 9].is_sorted_by(|a, b| a < b));

assert!([0].is_sorted_by(|a, b| true));
assert!([0].is_sorted_by(|a, b| false));

let empty: [i32; 0] = [];
assert!(empty.is_sorted_by(|a, b| false));
assert!(empty.is_sorted_by(|a, b| true));
1.82.0 · Source

pub fn is_sorted_by_key<'a, F, K>(&'a self, f: F) -> bool
where F: FnMut(&'a T) -> K, K: PartialOrd,

Checks if the elements of this slice are sorted using the given key extraction function.

Instead of comparing the slice’s elements directly, 此函数 compares the keys of the elements, as determined by f。 Apart 从 that, it’s equivalent 到 is_sorted; see its documentation 以获取更多信息。

§示例
assert!(["c", "bb", "aaa"].is_sorted_by_key(|s| s.len()));
assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs()));
1.52.0 · Source

pub fn partition_point<P>(&self, pred: P) -> usize
where P: FnMut(&T) -> bool,

Returns the index of the partition point according 到 the given predicate (the index of the first element of the second partition)。

此 slice is assumed 到 be partitioned according 到 the given predicate. This means that all elements 用于 which the predicate 返回 true are at the start of the slice 并 all elements 用于 which the predicate returns false are at the end. For example, [7, 15, 3, 5, 4, 12, 6] is partitioned under the predicate x % 2 != 0 (all odd numbers are at the start, all even at the end)。

If this slice is not partitioned, the returned result is unspecified 并 meaningless, as this method performs 一个 kind of binary search.

See also binary_search, binary_search_by, 并 binary_search_by_key

§示例
let v = [1, 2, 3, 3, 5, 6, 7];
let i = v.partition_point(|&x| x < 5);

assert_eq!(i, 4);
assert!(v[..i].iter().all(|&x| x < 5));
assert!(v[i..].iter().all(|&x| !(x < 5)));

If all elements of the slice match the predicate, including if the slice is empty, then the length of the slice will be returned:

let a = [2, 4, 8];
assert_eq!(a.partition_point(|x| x < &100), a.len());
let a: [i32; 0] = [];
assert_eq!(a.partition_point(|x| x < &100), 0);

If you want to insert an item to a sorted vector, while maintaining sort order:

let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
let num = 42;
let idx = s.partition_point(|&x| x <= num);
s.insert(idx, num);
assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
1.87.0 · Source

pub fn split_off<'a, R>(self: &mut &'a [T], range: R) -> Option<&'a [T]>
where R: OneSidedRange<usize>,

Removes the subslice corresponding 到 the given range 并 returns 一个 reference 到 it.

Returns None 并 does not modify the slice if the given range is out of bounds.

Note that this method only accepts one-sided ranges such as 2.。。.6, but not 2..6

§示例

Splitting off the first three elements of 一个 slice:

let mut slice: &[_] = &['a', 'b', 'c', 'd'];
let mut first_three = slice.split_off(..3).unwrap();

assert_eq!(slice, &['d']);
assert_eq!(first_three, &['a', 'b', 'c']);

Splitting off a slice starting with the third element:

let mut slice: &[_] = &['a', 'b', 'c', 'd'];
let mut tail = slice.split_off(2..).unwrap();

assert_eq!(slice, &['a', 'b']);
assert_eq!(tail, &['c', 'd']);

Getting None when range is out of bounds:

let mut slice: &[_] = &['a', 'b', 'c', 'd'];

assert_eq!(None, slice.split_off(5..));
assert_eq!(None, slice.split_off(..5));
assert_eq!(None, slice.split_off(..=4));
let expected: &[char] = &['a', 'b', 'c', 'd'];
assert_eq!(Some(expected), slice.split_off(..4));
1.87.0 · Source

pub fn split_off_mut<'a, R>( self: &mut &'a mut [T], range: R, ) -> Option<&'a mut [T]>
where R: OneSidedRange<usize>,

Removes the subslice corresponding 到 the given range 并 returns 一个 mutable reference 到 it.

Returns None 并 does not modify the slice if the given range is out of bounds.

Note that this method only accepts one-sided ranges such as 2.。。.6, but not 2..6

§示例

Splitting off the first three elements of 一个 slice:

let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
let mut first_three = slice.split_off_mut(..3).unwrap();

assert_eq!(slice, &mut ['d']);
assert_eq!(first_three, &mut ['a', 'b', 'c']);

Splitting off a slice starting with the third element:

let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
let mut tail = slice.split_off_mut(2..).unwrap();

assert_eq!(slice, &mut ['a', 'b']);
assert_eq!(tail, &mut ['c', 'd']);

Getting None when range is out of bounds:

let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];

assert_eq!(None, slice.split_off_mut(5..));
assert_eq!(None, slice.split_off_mut(..5));
assert_eq!(None, slice.split_off_mut(..=4));
let expected: &mut [_] = &mut ['a', 'b', 'c', 'd'];
assert_eq!(Some(expected), slice.split_off_mut(..4));
1.87.0 · Source

pub fn split_off_first<'a>(self: &mut &'a [T]) -> Option<&'a T>

Removes the first element of the slice 并 returns 一个 reference 到 it.

Returns None if the slice is empty.

§示例
let mut slice: &[_] = &['a', 'b', 'c'];
let first = slice.split_off_first().unwrap();

assert_eq!(slice, &['b', 'c']);
assert_eq!(first, &'a');
1.87.0 · Source

pub fn split_off_first_mut<'a>(self: &mut &'a mut [T]) -> Option<&'a mut T>

Removes the first element of the slice 并 returns 一个 mutable reference 到 it.

Returns None if the slice is empty.

§示例
let mut slice: &mut [_] = &mut ['a', 'b', 'c'];
let first = slice.split_off_first_mut().unwrap();
*first = 'd';

assert_eq!(slice, &['b', 'c']);
assert_eq!(first, &'d');
1.87.0 · Source

pub fn split_off_last<'a>(self: &mut &'a [T]) -> Option<&'a T>

Removes the last element of the slice 并 returns 一个 reference 到 it.

Returns None if the slice is empty.

§示例
let mut slice: &[_] = &['a', 'b', 'c'];
let last = slice.split_off_last().unwrap();

assert_eq!(slice, &['a', 'b']);
assert_eq!(last, &'c');
1.87.0 · Source

pub fn split_off_last_mut<'a>(self: &mut &'a mut [T]) -> Option<&'a mut T>

Removes the last element of the slice 并 returns 一个 mutable reference 到 it.

Returns None if the slice is empty.

§示例
let mut slice: &mut [_] = &mut ['a', 'b', 'c'];
let last = slice.split_off_last_mut().unwrap();
*last = 'd';

assert_eq!(slice, &['a', 'b']);
assert_eq!(last, &'d');
1.86.0 · Source

pub unsafe fn get_disjoint_unchecked_mut<I, const N: usize>( &mut self, indices: [I; N], ) -> [&mut <I as SliceIndex<[T]>>::Output; N]

Returns mutable references 到 many indices at once, without doing any checks.

An index can be either 一个 usize, 一个 Range 或 一个 RangeInclusive。 Note that this method takes an array, so all indices must be of the same type. If passed an array of usizes this method gives back an array of mutable references 到 single elements, while if passed an array of ranges it gives back an array of mutable references 到 slices.

For 一个 safe alternative see get_disjoint_mut

§Safety

调用 this method with overlapping 或 out-of-bounds indices is undefined behavior even if the resulting references are not 用.

§示例
let x = &mut [1, 2, 4];

unsafe {
    let [a, b] = x.get_disjoint_unchecked_mut([0, 2]);
    *a *= 10;
    *b *= 100;
}
assert_eq!(x, &[10, 2, 400]);

unsafe {
    let [a, b] = x.get_disjoint_unchecked_mut([0..1, 1..3]);
    a[0] = 8;
    b[0] = 88;
    b[1] = 888;
}
assert_eq!(x, &[8, 88, 888]);

unsafe {
    let [a, b] = x.get_disjoint_unchecked_mut([1..=2, 0..=0]);
    a[0] = 11;
    a[1] = 111;
    b[0] = 1;
}
assert_eq!(x, &[1, 11, 111]);
1.86.0 · Source

pub fn get_disjoint_mut<I, const N: usize>( &mut self, indices: [I; N], ) -> Result<[&mut <I as SliceIndex<[T]>>::Output; N], GetDisjointMutError>

Returns mutable references 到 many indices at once.

An index can be either 一个 usize, 一个 Range 或 一个 RangeInclusive。 Note that this method takes an array, so all indices must be of the same type. If passed an array of usizes this method gives back an array of mutable references 到 single elements, while if passed an array of ranges it gives back an array of mutable references 到 slices.

Returns an error if any index is out-of-bounds, 或 if there are overlapping indices. An empty range is not considered 到 overlap if it is located at the beginning 或 at the end of another range, but 被视为 到 overlap if it is located in the middle.

This method does 一个 O(n^2) 检查 到 检查 that there are no overlapping indices, so be careful when passing many indices.

§示例
let v = &mut [1, 2, 3];
if let Ok([a, b]) = v.get_disjoint_mut([0, 2]) {
    *a = 413;
    *b = 612;
}
assert_eq!(v, &[413, 2, 612]);

if let Ok([a, b]) = v.get_disjoint_mut([0..1, 1..3]) {
    a[0] = 8;
    b[0] = 88;
    b[1] = 888;
}
assert_eq!(v, &[8, 88, 888]);

if let Ok([a, b]) = v.get_disjoint_mut([1..=2, 0..=0]) {
    a[0] = 11;
    a[1] = 111;
    b[0] = 1;
}
assert_eq!(v, &[1, 11, 111]);
1.94.0 · Source

pub fn element_offset(&self, element: &T) -> Option<usize>

Returns the index that an element reference points 到.

Returns None if element does not point 到 the start of an element within the slice.

This method is useful 用于 extending slice iterators like slice::split

Note that this uses pointer arithmetic 并 does not compare elements。 To find the index of an element via comparison, use .iter().position() instead.

§Panics

Panics if T is zero-sized.

§示例

Basic usage:

let nums: &[u32] = &[1, 7, 1, 1];
let num = &nums[2];

assert_eq!(num, &1);
assert_eq!(nums.element_offset(num), Some(2));

Returning None with an unaligned element:

let arr: &[[u32; 2]] = &[[0, 1], [2, 3]];
let flat_arr: &[u32] = arr.as_flattened();

let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap();
let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap();

assert_eq!(ok_elm, &[0, 1]);
assert_eq!(weird_elm, &[1, 2]);

assert_eq!(arr.element_offset(ok_elm), Some(0)); // Points to element 0
assert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 1
Source

pub fn subslice_range(&self, subslice: &[T]) -> Option<Range<usize>>

🔬This is a nightly-only experimental API. (substr_range)

Returns the range of indices that 一个 subslice points 到.

Returns None if subslice does not point within the slice 或 if it is not aligned with the elements in the slice.

This method does not compare elements。 Instead, this method finds the location in the slice that subslice was obtained 从。 To find the index of 一个 subslice via comparison, instead use .windows().position()

This method is useful 用于 extending slice iterators like slice::split

Note that this may return 一个 false positive (either Some(0..0)Some(self.len()。.self.len())) if subslice has 一个 length of zero 并 points 到 the beginning 或 end of another, separate, slice.

§Panics

Panics if T is zero-sized.

§示例

Basic usage:

#![feature(substr_range)]

let nums = &[0, 5, 10, 0, 0, 5];

let mut iter = nums
    .split(|t| *t == 0)
    .map(|n| nums.subslice_range(n).unwrap());

assert_eq!(iter.next(), Some(0..0));
assert_eq!(iter.next(), Some(1..3));
assert_eq!(iter.next(), Some(4..4));
assert_eq!(iter.next(), Some(5..6));
Source

pub fn as_slice(&self) -> &[T]

🔬This is a nightly-only experimental API. (str_as_str)

Returns the same slice &[T]

This method is redundant when 用 directly on &[T], but it helps dereferencing other “container” types 到 slices, 用于 example Box<[T]>Arc<[T]>

Source

pub fn as_mut_slice(&mut self) -> &mut [T]

🔬This is a nightly-only experimental API. (str_as_str)

Returns the same slice &mut [T]

This method is redundant when 用 directly on &mut [T], but it helps dereferencing other “container” types 到 slices, 用于 example Box<[T]>MutexGuard<[T]>

1.79.0 · Source

pub fn utf8_chunks(&self) -> Utf8Chunks<'_>

Creates an iterator over the contiguous valid UTF-8 ranges of this slice, 并 the non-UTF-8 fragments in between.

,请参见 Utf8Chunk type 用于 documentation of the items yielded by this iterator.

§示例

This function formats arbitrary but mostly-UTF-8 bytes into Rust source code in the form of 一个 C-string literal (c"。。。")。

use std::fmt::Write as _;

pub fn cstr_literal(bytes: &[u8]) -> String {
    let mut repr = String::new();
    repr.push_str("c\"");
    for chunk in bytes.utf8_chunks() {
        for ch in chunk.valid().chars() {
            // Escapes \0, \t, \r, \n, \\, \', \", and uses \u{...} for non-printable characters.
            write!(repr, "{}", ch.escape_debug()).unwrap();
        }
        for byte in chunk.invalid() {
            write!(repr, "\\x{:02X}", byte).unwrap();
        }
    }
    repr.push('"');
    repr
}

fn main() {
    let lit = cstr_literal(b"\xferris the \xf0\x9f\xa6\x80\x07");
    let expected = stringify!(c"\xFErris the 🦀\u{7}");
    assert_eq!(lit, expected);
}
1.0.0 · Source

pub fn sort(&mut self)
where T: Ord,

Sorts the slice in ascending order, preserving initial order of equal elements.

This sort is stable (i.e., does not reorder equal elements) 并 O(n * log(n)) worst-case.

If the implementation of Ord 用于 T does not implement 一个 total order, 函数 may panic; even if 函数 exits normally, the resulting order of elements in the slice is unspecified. See also the note on panicking below.

When applicable, unstable sorting is preferred because it is generally faster than stable sorting 并 it doesn’t allocate auxiliary memory. See sort_unstable。 此 exception are partially sorted slices, which may be better served with slice::sort

Sorting types that only implement PartialOrd such as f32f64 require additional precautions. For example, f32::NAN != f32::NAN, which doesn’t fulfill the reflexivity requirement of Ord。 By using an alternative comparison function with slice::sort_by such as f32::total_cmpf64::total_cmp that defines 一个 total order users can sort slices containing floating-point values. Alternatively, if all values in the slice are guaranteed 到 be in 一个 subset 用于 which PartialOrd::partial_cmp forms 一个 total order, it’s possible 到 sort the slice with sort_by(|一个, b| 一个.partial_cmp(b).unwrap())

§Current implementation

此 current implementation is based on driftsort by Orson Peters 并 Lukas Bergdoll, which combines the fast average case of quicksort with the fast worst case 并 partial run detection of mergesort, achieving linear time on fully sorted 并 reversed inputs. On inputs with k distinct elements, the expected time 到 sort 数据 is O(n * log(k))。

此 auxiliary memory allocation behavior depends on 输入 length. Short slices are handled without allocation, medium sized slices allocate self.len() 并 beyond that it clamps at self.len() / 2

§Panics

May panic if the implementation of Ord 用于 T does not implement 一个 total order, 或 if the Ord implementation itself panics.

All safe functions on slices preserve the invariant that even if 函数 panics, all original elements will remain in the slice 并 any possible modifications via interior mutability are observed in 输入. This ensures that recovery code (用于 instance inside of 一个 Drop 或 following 一个 catch_unwind) will still have access 到 all the original elements. For instance, if the slice belongs 到 一个 Vec, the Vec::drop method , able 到 dispose of all contained elements.

§示例
let mut v = [4, -5, 1, -3, 2];

v.sort();
assert_eq!(v, [-5, -3, 1, 2, 4]);
1.0.0 · Source

pub fn sort_by<F>(&mut self, compare: F)
where F: FnMut(&T, &T) -> Ordering,

Sorts the slice in ascending order with 一个 comparison function, preserving initial order of equal elements.

This sort is stable (i.e., does not reorder equal elements) 并 O(n * log(n)) worst-case.

If the comparison function compare does not implement 一个 total order, 函数 may panic; even if 函数 exits normally, the resulting order of elements in the slice is unspecified. See also the note on panicking below.

For example |一个, b| (一个 - b).cmp(一个) 是 comparison function , neither transitive nor reflexive nor total, 一个 < b < c < 一个 with 一个 = 1, b = 2, c = 3。 For more information 并 examples see the Ord documentation.

§Current implementation

此 current implementation is based on driftsort by Orson Peters 并 Lukas Bergdoll, which combines the fast average case of quicksort with the fast worst case 并 partial run detection of mergesort, achieving linear time on fully sorted 并 reversed inputs. On inputs with k distinct elements, the expected time 到 sort 数据 is O(n * log(k))。

此 auxiliary memory allocation behavior depends on 输入 length. Short slices are handled without allocation, medium sized slices allocate self.len() 并 beyond that it clamps at self.len() / 2

§Panics

May panic if compare does not implement 一个 total order, 或 if compare itself panics.

All safe functions on slices preserve the invariant that even if 函数 panics, all original elements will remain in the slice 并 any possible modifications via interior mutability are observed in 输入. This ensures that recovery code (用于 instance inside of 一个 Drop 或 following 一个 catch_unwind) will still have access 到 all the original elements. For instance, if the slice belongs 到 一个 Vec, the Vec::drop method , able 到 dispose of all contained elements.

§示例
let mut v = [4, -5, 1, -3, 2];
v.sort_by(|a, b| a.cmp(b));
assert_eq!(v, [-5, -3, 1, 2, 4]);

// reverse sorting
v.sort_by(|a, b| b.cmp(a));
assert_eq!(v, [4, 2, 1, -3, -5]);
1.7.0 · Source

pub fn sort_by_key<K, F>(&mut self, f: F)
where F: FnMut(&T) -> K, K: Ord,

Sorts the slice in ascending order with 一个 key extraction function, preserving initial order of equal elements.

This sort is stable (i.e., does not reorder equal elements) 并 O(m * n * log(n)) worst-case, where the key function is O(m)。

If the implementation of Ord 用于 K does not implement 一个 total order, 函数 may panic; even if 函数 exits normally, the resulting order of elements in the slice is unspecified. See also the note on panicking below.

§Current implementation

此 current implementation is based on driftsort by Orson Peters 并 Lukas Bergdoll, which combines the fast average case of quicksort with the fast worst case 并 partial run detection of mergesort, achieving linear time on fully sorted 并 reversed inputs. On inputs with k distinct elements, the expected time 到 sort 数据 is O(n * log(k))。

此 auxiliary memory allocation behavior depends on 输入 length. Short slices are handled without allocation, medium sized slices allocate self.len() 并 beyond that it clamps at self.len() / 2

§Panics

May panic if the implementation of Ord 用于 K does not implement 一个 total order, 或 if the Ord implementation 或 the key-function f panics.

All safe functions on slices preserve the invariant that even if 函数 panics, all original elements will remain in the slice 并 any possible modifications via interior mutability are observed in 输入. This ensures that recovery code (用于 instance inside of 一个 Drop 或 following 一个 catch_unwind) will still have access 到 all the original elements. For instance, if the slice belongs 到 一个 Vec, the Vec::drop method , able 到 dispose of all contained elements.

§示例
let mut v = [4i32, -5, 1, -3, 2];

v.sort_by_key(|k| k.abs());
assert_eq!(v, [1, 2, -3, 4, -5]);
1.34.0 · Source

pub fn sort_by_cached_key<K, F>(&mut self, f: F)
where F: FnMut(&T) -> K, K: Ord,

Sorts the slice in ascending order with 一个 key extraction function, preserving initial order of equal elements.

This sort is stable (i.e., does not reorder equal elements) 并 O(m * n + n * log(n)) worst-case, where the key function is O(m)。

During sorting, the key function is called at most once per element, by using temporary storage 到 remember the results of key evaluation. 此 order of calls 到 the key function is unspecified 并 may change in future versions of 标准 library.

If the implementation of Ord 用于 K does not implement 一个 total order, 函数 may panic; even if 函数 exits normally, the resulting order of elements in the slice is unspecified. See also the note on panicking below.

For simple key functions (e.g., functions that are property accesses 或 basic operations), sort_by_key is likely 到 be faster.

§Current implementation

此 current implementation is based on instruction-parallel-network sort by Lukas Bergdoll, which combines the fast average case of randomized quicksort with the fast worst case of heapsort, while achieving linear time on fully sorted 并 reversed inputs. And O(k * log(n)) where k 是 number of distinct elements in 输入. It leverages superscalar out-of-order execution capabilities commonly found in CPUs, 到 efficiently perform the operation.

In the worst case, the 算法 allocates temporary storage in 一个 Vec<(K, usize)> the length of the slice.

§Panics

May panic if the implementation of Ord 用于 K does not implement 一个 total order, 或 if the Ord implementation panics.

All safe functions on slices preserve the invariant that even if 函数 panics, all original elements will remain in the slice 并 any possible modifications via interior mutability are observed in 输入. This ensures that recovery code (用于 instance inside of 一个 Drop 或 following 一个 catch_unwind) will still have access 到 all the original elements. For instance, if the slice belongs 到 一个 Vec, the Vec::drop method , able 到 dispose of all contained elements.

§示例
let mut v = [4i32, -5, 1, -3, 2, 10];

// Strings are sorted by lexicographical order.
v.sort_by_cached_key(|k| k.to_string());
assert_eq!(v, [-3, -5, 1, 10, 2, 4]);
1.0.0 · Source

pub fn to_vec(&self) -> Vec<T>
where T: Clone,

Copies self into 新 Vec

§示例
let s = [10, 40, 30];
let x = s.to_vec();
// Here, `s` and `x` can be modified independently.
Source

pub fn to_vec_in<A>(&self, alloc: A) -> Vec<T, A>
where A: Allocator, T: Clone,

🔬This is a nightly-only experimental API. (allocator_api)

Copies self into 新 Vec with an allocator.

§示例
#![feature(allocator_api)]

use std::alloc::System;

let s = [10, 40, 30];
let x = s.to_vec_in(System);
// Here, `s` and `x` can be modified independently.
1.40.0 · Source

pub fn repeat(&self, n: usize) -> Vec<T>
where T: Copy,

Creates 一个 vector by copying 一个 slice n times.

§Panics

This function will panic if the capacity would overflow.

§示例
assert_eq!([1, 2].repeat(3), vec![1, 2, 1, 2, 1, 2]);

A panic upon overflow:

// this will panic at runtime
b"0123456789abcdef".repeat(usize::MAX);
1.0.0 · Source

pub fn concat<Item>(&self) -> <[T] as Concat<Item>>::Output
where [T]: Concat<Item>, Item: ?Sized,

Flattens 一个 slice of T into 一个 single value Self::Output

§示例
assert_eq!(["hello", "world"].concat(), "helloworld");
assert_eq!([[1, 2], [3, 4]].concat(), [1, 2, 3, 4]);
1.3.0 · Source

pub fn join<Separator>( &self, sep: Separator, ) -> <[T] as Join<Separator>>::Output
where [T]: Join<Separator>,

Flattens 一个 slice of T into 一个 single value Self::Output, placing 一个 given separator between each.

§示例
assert_eq!(["hello", "world"].join(" "), "hello world");
assert_eq!([[1, 2], [3, 4]].join(&0), [1, 2, 0, 3, 4]);
assert_eq!([[1, 2], [3, 4]].join(&[0, 0][..]), [1, 2, 0, 0, 3, 4]);
1.0.0 · Source

pub fn connect<Separator>( &self, sep: Separator, ) -> <[T] as Join<Separator>>::Output
where [T]: Join<Separator>,

👎Deprecated since 1.3.0: renamed to join

Flattens 一个 slice of T into 一个 single value Self::Output, placing 一个 given separator between each.

§示例
assert_eq!(["hello", "world"].connect(" "), "hello world");
assert_eq!([[1, 2], [3, 4]].connect(&0), [1, 2, 0, 3, 4]);
1.23.0 · Source

pub fn to_ascii_uppercase(&self) -> Vec<u8>

Returns 一个 vector containing 一个 copy of this slice where each byte is mapped 到 its ASCII upper case equivalent.

ASCII letters ‘一个’ 到 ‘z’ are mapped 到 ‘A’ 到 ‘Z’, but non-ASCII letters are unchanged.

To uppercase the value in-place, use make_ascii_uppercase

1.23.0 · Source

pub fn to_ascii_lowercase(&self) -> Vec<u8>

Returns 一个 vector containing 一个 copy of this slice where each byte is mapped 到 its ASCII lower case equivalent.

ASCII letters ‘A’ 到 ‘Z’ are mapped 到 ‘一个’ 到 ‘z’, but non-ASCII letters are unchanged.

To lowercase the value in-place, use make_ascii_lowercase

Trait 实现§

Source§

impl Deref for BorrowedPayload<'_>

Source§

type Target = [u8]

解引用后得到的类型。
Source§

fn deref(&self) -> &Self::Target

解引用此值。
Source§

impl DerefMut for BorrowedPayload<'_>

Source§

fn deref_mut(&mut self) -> &mut Self::Target

以可变方式解引用此值。

自动 Trait 实现§

§

impl<'a> Freeze for BorrowedPayload<'a>

§

impl<'a> RefUnwindSafe for BorrowedPayload<'a>

§

impl<'a> Send for BorrowedPayload<'a>

§

impl<'a> Sync for BorrowedPayload<'a>

§

impl<'a> Unpin for BorrowedPayload<'a>

§

impl<'a> UnsafeUnpin for BorrowedPayload<'a>

§

impl<'a> !UnwindSafe for BorrowedPayload<'a>

Blanket 实现§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. 更多信息
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows 从 an owned value. 更多信息
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows 从 an owned value. 更多信息
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

原样返回传入的参数。

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::从(self)

That is, this conversion is whatever the implementation of From<T> 用于 U 的实现方式。

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
此 target type on which the method may be called.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

转换出错时返回的类型。
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

执行转换。
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

转换出错时返回的类型。
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

执行转换。