跳到主要内容

ConnectionId

搜索

结构体 ConnectionId 

源代码
pub struct ConnectionId { /* private fields */ }
展开描述

连接的协议级标识符。

主要用于通过 Wireshark 之类的工具在链路上识别该连接的数据包。

实现§

源代码§

impl ConnectionId

源代码

pub fn new(bytes: &[u8]) -> ConnectionId

从字节数组构造一个 cid

源代码

pub fn from_buf(buf: &mut (impl Buf + ?Sized), len: usize) -> ConnectionId

通过从 Buf 读取 len 个字节来构造 cid

调用者需要保证 buf.remaining() >= len

Methods from Deref<Target = [u8]>§

1.23.0 · 源代码

pub fn is_ascii(&self) -> bool

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

空切片返回 true

源代码

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

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

若此切片 is_ascii,则将其作为 ASCII 字符 的切片返回;否则返回 None

源代码

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

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

将此字节切片转换为 ASCII 字符切片,但不检查它们是否合法。

§安全性

切片中的每个字节都必须位于 0..=127,否则属于未定义行为。

1.23.0 · 源代码

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

检查两个切片是否在不区分 ASCII 大小写的情况下相等。

等价于 to_ascii_lowercase(a) == to_ascii_lowercase(b),但无需分配并复制临时变量。

1.23.0 · 源代码

pub fn make_ascii_uppercase(&mut self)

将此切片就地转换为对应的大写 ASCII 形式。

ASCII 字母 az 会被映射为 AZ,但非 ASCII 字母保持不变。

若希望返回一个新的全大写副本而不修改原切片,请使用 to_ascii_uppercase

1.23.0 · 源代码

pub fn make_ascii_lowercase(&mut self)

将此切片就地转换为对应的小写 ASCII 形式。

ASCII 字母 AZ 会被映射为 az,但非 ASCII 字母保持不变。

若希望返回一个新的全小写副本而不修改原切片,请使用 to_ascii_lowercase

1.60.0 · 源代码

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

返回一个迭代器,产出此切片的转义形式,按 ASCII 字符串处理。

§示例
[EXAMPLE]
1.80.0 · 源代码

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

返回一个移除了开头 ASCII 空白字节的字节切片。

“空白”采用 u8::is_ascii_whitespace 的定义。

§示例
[EXAMPLE]
1.80.0 · 源代码

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

返回一个移除了末尾 ASCII 空白字节的字节切片。

“空白”采用 u8::is_ascii_whitespace 的定义。

§示例
[EXAMPLE]
1.80.0 · 源代码

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

返回一个同时移除了开头和末尾 ASCII 空白字节的字节切片。

“空白”采用 u8::is_ascii_whitespace 的定义。

§示例
[EXAMPLE]
1.0.0 · 源代码

pub fn len(&self) -> usize

返回切片中的元素数量。

§示例
[EXAMPLE]
1.0.0 · 源代码

pub fn is_empty(&self) -> bool

若切片长度为 0 则返回 true

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

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

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

返回切片的第一个元素;若切片为空则返回 None

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

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

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

返回切片第一个元素的可变引用;若切片为空则返回 None

§Examples
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 · 源代码

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

返回第一个元素以及切片中剩余的所有元素;若切片为空则返回 None

§Examples
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 · 源代码

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

返回第一个元素以及切片中剩余的所有元素;若切片为空则返回 None

§Examples
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 · 源代码

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

返回最后一个元素以及切片中剩余的所有元素;若切片为空则返回 None

§Examples
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 · 源代码

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

返回最后一个元素以及切片中剩余的所有元素;若切片为空则返回 None

§Examples
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 · 源代码

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

返回切片的最后一个元素;若切片为空则返回 None

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

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

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

返回切片最后一个元素的可变引用;若切片为空则返回 None

§Examples
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 · 源代码

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

返回切片前 N 个元素的数组引用。

若切片长度小于 N,则返回 None

§Examples
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 · 源代码

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

返回切片前 N 个元素的可变数组引用。

若切片长度小于 N,则返回 None

§Examples
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 · 源代码

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

返回切片前 N 个元素的数组引用以及剩余切片。

若切片长度小于 N,则返回 None

§Examples
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 · 源代码

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

返回切片前 N 个元素的可变数组引用以及剩余切片。

若切片长度小于 N,则返回 None

§Examples
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 · 源代码

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

返回切片末尾 N 个元素的数组引用以及剩余切片。

若切片长度小于 N,则返回 None

§Examples
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 · 源代码

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

返回切片末尾 N 个元素的可变数组引用以及剩余切片。

若切片长度小于 N,则返回 None

§Examples
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 · 源代码

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

返回切片末尾 N 个元素的数组引用。

若切片长度小于 N,则返回 None

§Examples
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 · 源代码

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

返回切片末尾 N 个元素的可变数组引用。

若切片长度小于 N,则返回 None

§Examples
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 · 源代码

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

返回位于给定索引处的元素,或在越界时返回 None

§示例
[EXAMPLE]
1.0.0 · 源代码

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

依据索引类型返回对一个元素或子切片的可变引用(详见 get);若索引越界则返回 None

§Examples
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 · 源代码

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

返回对一个元素或子切片的引用,不进行边界检查。

如需安全版本,请参阅 get

§安全性

即便不使用所得到的引用,使用越界索引调用本方法也属于未定义行为

你可以把它理解为 .get(index).unwrap_unchecked()。调用 .get_unchecked(len) 即便立即转换成指针也是 UB;同理,调用 .get_unchecked(..len + 1).get_unchecked(..=len) 等也是 UB。

§示例
[EXAMPLE]
1.0.0 · 源代码

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

返回对一个元素或子切片的可变引用,不进行边界检查。

如需安全版本,请参阅 get_mut

§安全性

即便不使用所得到的引用,使用越界索引调用本方法也属于未定义行为

你可以把它理解为 .get_mut(index).unwrap_unchecked()。调用 .get_unchecked_mut(len) 即便立即转换成指针也是 UB;同理,调用 .get_unchecked_mut(..len + 1).get_unchecked_mut(..=len) 等也是 UB。

§示例
[EXAMPLE]
1.0.0 · 源代码

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

返回指向切片起始地址的裸指针。

调用方必须确保切片存活,且不能通过该指针在 self 范围之外访问内存。

1.0.0 · 源代码

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

返回指向切片起始地址的可写裸指针。

调用方必须确保切片存活,且不能通过该指针在 self 范围之外访问内存。

1.48.0 · 源代码

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

返回包含切片中所有有效索引的“指针范围”。

1.48.0 · 源代码

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

返回覆盖该切片范围的两个不安全的可变指针。

返回的范围是半开区间,意思是结束指针指向切片最后一个元素之后的位置。这样一来,空切片由两个相等的指针表示,而两指针之差就是切片的长度。

关于使用这些指针时的注意事项,请参阅 as_mut_ptr。结束指针需要额外小心,因为它并不指向切片中的有效元素。

本函数适用于与使用两个指针表示内存中一段元素的外部接口(常见于 C++)交互。

1.93.0 · 源代码

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

将切片转换为共享引用,指向底层数组。

若切片长度正好等于数组长度,则返回 Some;否则返回 None

1.93.0 · 源代码

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

将可变切片转换为可变引用,指向底层数组。

若切片长度正好等于数组长度,则返回 Some;否则返回 None

1.0.0 · 源代码

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

交换切片中的两个元素。

a 等于 b,则保证元素值不会改变。

§参数
  • a — 第一个元素的索引
  • b — 第二个元素的索引
§Panics

ab 越界则 panic。

§示例
[EXAMPLE]
源代码

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

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

交换切片中的两个元素,无需进行边界检查。

§安全性

调用方必须确保 ab 均小于切片长度,否则属于未定义行为。

1.0.0 · 源代码

pub fn reverse(&mut self)

将切片中的元素顺序原地反转。

§示例
[EXAMPLE]
1.0.0 · 源代码

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

返回一个遍历切片的迭代器。

1.0.0 · 源代码

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

返回一个可变迭代器,允许修改每个元素。

1.0.0 · 源代码

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

返回一个迭代器,遍历长度为 size 的所有连续窗口。各窗口相互重叠。若切片短于 size,则迭代器不产生任何元素。

§Panics

size 为零则 panic。

§Examples
let slice = ['l', 'o', 'r', 'e', 'm'];
let mut iter = slice.windows(3);
assert_eq!(iter.next().unwrap(), &['l', 'o', 'r']);
assert_eq!(iter.next().unwrap(), &['o', 'r', 'e']);
assert_eq!(iter.next().unwrap(), &['r', 'e', 'm']);
assert!(iter.next().is_none());

If the slice is shorter than size:

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 · 源代码

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

返回一个迭代器,每次遍历切片的 chunk_size 个元素,从切片开头开始。

各块为切片且互不重叠。若 chunk_size 不能整除切片长度,最后一块的长度将不等于 chunk_size

若希望迭代器总是返回长度恰为 chunk_size 的块,请参阅 chunks_exact;若希望从切片末尾开始,请参阅 rchunks

chunk_size 为编译期常量,建议改用 as_chunks,它会返回长度恰为该常量的数组引用,而非切片引用。

§Panics

chunk_size 为零则 panic。

§Examples
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 · 源代码

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

返回一个迭代器,每次遍历切片的 chunk_size 个元素,从切片开头开始。

各块为可变切片且互不重叠。若 chunk_size 不能整除切片长度,最后一块的长度将不等于 chunk_size

若希望迭代器总是返回长度恰为 chunk_size 的块,请参阅 chunks_exact_mut;若希望从切片末尾开始,请参阅 rchunks_mut

chunk_size 为编译期常量,建议改用 as_chunks_mut,它会返回长度恰为该常量的数组引用,而非切片引用。

§Panics

chunk_size 为零则 panic。

§Examples
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 · 源代码

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

返回一个迭代器,每次遍历切片的 chunk_size 个元素,从切片开头开始。

各块为切片且互不重叠。若 chunk_size 不能整除切片长度,末尾最多 chunk_size-1 个元素将被略过,可通过迭代器的 remainder 函数取回。

由于每块恰好包含 chunk_size 个元素,编译器通常能比 chunks 更优化所生成的代码。

若希望迭代器将剩余元素也作为较小的块返回,请参阅 chunks;若希望从切片末尾开始,请参阅 rchunks_exact

chunk_size 为编译期常量,建议改用 as_chunks

§Panics

chunk_size 为零则 panic。

§Examples
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 · 源代码

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

返回一个迭代器,每次遍历切片的 chunk_size 个元素,从切片开头开始。

各块为可变切片且互不重叠。若 chunk_size 不能整除切片长度,末尾最多 chunk_size-1 个元素将被略过,可通过迭代器的 into_remainder 函数取回。

由于每块恰好包含 chunk_size 个元素,编译器通常能比 chunks_mut 更优化所生成的代码。

若希望迭代器将剩余元素也作为较小的块返回,请参阅 chunks_mut;若希望从切片末尾开始,请参阅 rchunks_exact_mut

chunk_size 为编译期常量,建议改用 as_chunks_mut

§Panics

chunk_size 为零则 panic。

§Examples
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 · 源代码

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

将切片拆分为 N-元素数组的切片,假定不存在余数。

1.88.0 · 源代码

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

尝试将切片拆分为 N-元素数组的切片,余数切片长度严格小于 N

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 · 源代码

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

从切片末尾开始,将切片拆分为 N-元素数组的切片,余数切片长度严格小于 N

1.88.0 · 源代码

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

将切片拆分为 N-元素数组的切片,假定不存在余数(可变版本)。

1.88.0 · 源代码

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

as_chunks 类似,但产生的是可变切片。

1.88.0 · 源代码

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

将切片拆分为一个由 N-元素数组组成的切片(从切片末尾开始)以及一个长度严格小于 N 的余数切片。

余数部分在除法意义下是有意义的。给定 let (remainder, chunks) = slice.as_rchunks_mut(),那么:

  • remainder.len() 等于 slice.len() % N
  • chunks.len() 等于 slice.len() / N
  • slice.len() 等于 chunks.len() * N + remainder.len()

可以使用 as_flattened_mut 把 chunks 重新展平为 T 切片。

§Panics

N 为零则 panic。

注意此检查针对的是 const 泛型参数而非运行时值,因此某一具体单态化要么总是 panic、要么从不 panic。

§示例
[EXAMPLE]
1.94.0 · 源代码

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

返回一个迭代器,按长度为 N 的重叠窗口遍历切片,从切片开头开始。

这是 windows 的 const 泛型等价物。

N 大于切片大小,则不返回任何窗口。

§Panics

N 为零则 panic。

注意此检查针对的是 const 泛型参数而非运行时值,因此某一具体单态化要么总是 panic、要么从不 panic。

§示例
[EXAMPLE]
1.31.0 · 源代码

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

返回一个迭代器,每次遍历切片的 chunk_size 个元素,从切片末尾开始。

各块为切片且互不重叠。若 chunk_size 不能整除切片长度,最后一块的长度将不等于 chunk_size

若希望迭代器总是返回长度恰为 chunk_size 的块,请参阅 rchunks_exact;若希望从切片开头开始,请参阅 chunks

chunk_size 为编译期常量,建议改用 as_rchunks

§Panics

chunk_size 为零则 panic。

§Examples
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 · 源代码

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

返回一个迭代器,每次遍历切片的 chunk_size 个元素,从切片末尾开始。

各块为可变切片且互不重叠。若 chunk_size 不能整除切片长度,最后一块的长度将不等于 chunk_size

若希望迭代器总是返回长度恰为 chunk_size 的块,请参阅 rchunks_exact_mut;若希望从切片开头开始,请参阅 chunks_mut

chunk_size 为编译期常量,建议改用 as_rchunks_mut

§Panics

chunk_size 为零则 panic。

§Examples
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 · 源代码

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

返回一个迭代器,每次遍历切片的 chunk_size 个元素,从切片末尾开始。

各块为切片且互不重叠。若 chunk_size 不能整除切片长度,开头最多 chunk_size-1 个元素将被略过,可通过迭代器的 remainder 函数取回。

由于每块恰好包含 chunk_size 个元素,编译器通常能比 rchunks 更优化所生成的代码。

若希望迭代器将剩余元素也作为较小的块返回,请参阅 rchunks;若希望从切片开头开始,请参阅 chunks_exact

chunk_size 为编译期常量,建议改用 as_rchunks

§Panics

chunk_size 为零则 panic。

§Examples
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 · 源代码

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

返回一个迭代器,每次遍历切片的 chunk_size 个元素,从切片末尾开始。

各块为可变切片且互不重叠。若 chunk_size 不能整除切片长度,开头最多 chunk_size-1 个元素将被略过,可通过迭代器的 into_remainder 函数取回。

由于每块恰好包含 chunk_size 个元素,编译器通常能比 chunks_mut 更优化所生成的代码。

若希望迭代器将剩余元素也作为较小的块返回,请参阅 rchunks_mut;若希望从切片开头开始,请参阅 chunks_exact_mut

chunk_size 为编译期常量,建议改用 as_rchunks_mut

§Panics

chunk_size 为零则 panic。

§示例
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 · 源代码

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

返回一个从切片开头开始、按相邻相等元素分组的迭代器。

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 · 源代码

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

返回一个从切片开头开始、按相邻相等元素分组的可变迭代器。

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 · 源代码

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

将切片在给定索引处一分为二。

1.0.0 · 源代码

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

将可变切片在给定索引处一分为二。

1.79.0 · 源代码

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

在某个索引处将切片一分为二,不进行边界检查。

第一部分包含区间 [0, mid) 中的所有索引(不含 mid 本身),第二部分包含 [mid, len) 中的所有索引(不含 len 本身)。

如需安全版本,请参阅 split_at

§安全性

即便不使用所得到的引用,使用越界索引调用本方法也属于未定义行为。调用方必须保证 0 <= mid <= self.len()

§示例
[EXAMPLE]
1.79.0 · 源代码

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

在某个索引处将可变切片一分为二,不进行边界检查。

第一部分包含区间 [0, mid) 中的所有索引(不含 mid 本身),第二部分包含 [mid, len) 中的所有索引(不含 len 本身)。

如需安全版本,请参阅 split_at_mut

§安全性

即便不使用所得到的引用,使用越界索引调用本方法也属于未定义行为。调用方必须保证 0 <= mid <= self.len()

§示例
[EXAMPLE]
1.80.0 · 源代码

pub fn split_at_checked(&self, mid: usize) -> Option<(&[T], &[T])>

在某个索引处将切片一分为二;若切片过短则返回 None

mid ≤ len,返回一对切片,其中第一段包含区间 [0, mid) 中的所有索引(不含 mid 本身),第二段包含 [mid, len) 中的所有索引(不含 len 本身)。

否则,若 mid > len,返回 None

§Examples
let v = [1, -2, 3, -4, 5, -6];

{
   let (left, right) = v.split_at_checked(0).unwrap();
   assert_eq!(left, []);
   assert_eq!(right, [1, -2, 3, -4, 5, -6]);
}

{
    let (left, right) = v.split_at_checked(2).unwrap();
    assert_eq!(left, [1, -2]);
    assert_eq!(right, [3, -4, 5, -6]);
}

{
    let (left, right) = v.split_at_checked(6).unwrap();
    assert_eq!(left, [1, -2, 3, -4, 5, -6]);
    assert_eq!(right, []);
}

assert_eq!(None, v.split_at_checked(7));
1.80.0 · 源代码

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

在某个索引处将可变切片一分为二;若切片过短则返回 None

mid ≤ len,返回一对切片,其中第一段包含区间 [0, mid) 中的所有索引(不含 mid 本身),第二段包含 [mid, len) 中的所有索引(不含 len 本身)。

否则,若 mid > len,返回 None

§Examples
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 · 源代码

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

返回一个迭代器,遍历由满足 pred 的元素分隔开的子切片。匹配元素本身不包含在子切片中。

§Examples
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 · 源代码

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

返回一个迭代器,遍历由满足 pred 的元素分隔开的可变子切片。匹配元素本身不包含在子切片中。

§Examples
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 · 源代码

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

返回一个迭代器,遍历由满足 pred 的元素分隔开的子切片。匹配元素作为终止符包含在前一个子切片的末尾。

§Examples
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 · 源代码

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

返回一个迭代器,遍历由满足 pred 的元素分隔开的可变子切片。匹配元素作为终止符包含在前一个子切片中。

§Examples
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 · 源代码

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

返回一个迭代器,从切片末尾开始向前遍历由满足 pred 的元素分隔开的子切片。匹配元素本身不包含在子切片中。

§Examples
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 · 源代码

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

返回一个迭代器,从切片末尾开始向前遍历由满足 pred 的元素分隔开的可变子切片。匹配元素本身不包含在子切片中。

§Examples
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 · 源代码

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

返回一个迭代器,至多产出 n 个由 pat 匹配的子切片。

1.0.0 · 源代码

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

返回一个迭代器,至多产出 n 个由 pat 匹配的可变子切片。

1.0.0 · 源代码

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

返回一个从右端开始的迭代器,至多产出 n 个由 pat 匹配的子切片。

1.0.0 · 源代码

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

返回一个从右端开始的迭代器,至多产出 n 个由 pat 匹配的可变子切片。

源代码

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)

在第一个满足给定谓词的元素处将切片一分为二。

若切片中存在匹配的元素,则返回该匹配项之前的前缀和之后的后缀。匹配项本身不在结果中。若没有任何元素匹配,则返回 None

§示例
[EXAMPLE]
源代码

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)

在最后一个满足给定谓词的元素处将切片一分为二。

若切片中存在匹配的元素,则返回该匹配项之前的前缀和之后的后缀。匹配项本身不在结果中。若没有任何元素匹配,则返回 None

§示例
[EXAMPLE]
1.0.0 · 源代码

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

若切片包含具有给定值的元素则返回 true

该操作的时间复杂度为 O(n)。

注意,若切片已排序,使用 binary_search 可能更快。

§Examples
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 · 源代码

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

needle 是切片的前缀或与切片相等则返回 true

§Examples
let v = [10, 40, 30];
assert!(v.starts_with(&[10]));
assert!(v.starts_with(&[10, 40]));
assert!(v.starts_with(&v));
assert!(!v.starts_with(&[50]));
assert!(!v.starts_with(&[10, 50]));

Always returns true if needle is an empty slice:

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

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

needle 是切片的后缀或与切片相等则返回 true

§Examples
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 · 源代码

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

如果切片以 prefix 开头则返回去掉前缀后的子切片,否则返回 None

1.51.0 · 源代码

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

如果切片以 suffix 结尾则返回去掉后缀后的子切片,否则返回 None

源代码

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)

返回一个去除了前缀和后缀的子切片。

若切片以 prefix 开头且以 suffix 结尾,则返回介于前缀之后、后缀之前的那段子切片,并包装在 Some 中返回。

若切片不以 prefix 开头或不以 suffix 结尾,则返回 None

§示例
[EXAMPLE]
源代码

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)

返回一个去除了可选前缀的子切片。

若切片以 prefix 开头,则返回去掉该前缀后的子切片。若 prefix 为空或切片不以 prefix 开头,则直接返回原切片。若 prefix 与原切片相等,则返回空切片。

§示例
[EXAMPLE]
源代码

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)

返回一个去除了可选后缀的子切片。

若切片以 suffix 结尾,则返回去掉该后缀后的子切片。若 suffix 为空或切片不以 suffix 结尾,则直接返回原切片。若 suffix 与原切片相等,则返回空切片。

§示例
[EXAMPLE]

二分查找切片中等于给定元素的索引。

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 · 源代码

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

二分查找切片,使用给定的比较函数。

1.10.0 · 源代码

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,

二分查找切片,给定一个可以从元素派生的搜索键。

1.20.0 · 源代码

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

对切片进行原地排序。

此排序不稳定,相等的元素相对顺序可能被打乱;平均与最坏情况时间复杂度均为 O(n * log(n)),空间复杂度为 O(1)

1.20.0 · 源代码

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

使用给定的比较函数对切片进行原地不稳定排序。

1.20.0 · 源代码

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

使用从元素派生的键对切片进行原地不稳定排序。

源代码

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)

对切片中的指定区间进行不稳定的部分排序。

完成后,对指定区间 start..end 保证:

  1. self[..start] 中的每个元素都小于等于
  2. self[start..end] 中的每个元素(已排序),并且后者小于等于
  3. self[end..] 中的每个元素。

此部分排序是不稳定的,意味着指定区间内的相等元素顺序可能被重排。指定区间外的元素顺序也可能被重排,但上述保证依然成立。

此部分排序是原地(不分配)的,最坏复杂度为 O(n + k * log(k)),其中 n 为切片长度,k 为指定区间长度。

实现细节请参阅 sort_unstable 的文档。

§Panics

Ord 的实现并非全序、或其实现本身 panic、或指定区间越界时,可能 panic。

§示例
[EXAMPLE]
源代码

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)

使用给定的比较函数对切片中的指定区间进行不稳定的部分排序。

完成后,对指定区间 start..end 保证:

  1. self[..start] 中的每个元素都小于等于
  2. self[start..end] 中的每个元素(已排序),并且后者小于等于
  3. self[end..] 中的每个元素。

此部分排序是不稳定的,意味着指定区间内的相等元素顺序可能被重排。指定区间外的元素顺序也可能被重排,但上述保证依然成立。

此部分排序是原地(不分配)的,最坏复杂度为 O(n + k * log(k)),其中 n 为切片长度,k 为指定区间长度。

实现细节请参阅 sort_unstable_by 的文档。

§Panics

compare 不是全序、或其本身 panic、或指定区间越界时,可能 panic。

§示例
[EXAMPLE]
源代码

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)

使用给定的键提取函数对切片中的指定区间进行不稳定的部分排序。

完成后,对指定区间 start..end 保证:

  1. self[..start] 中的每个元素都小于等于
  2. self[start..end] 中的每个元素(已按对应键排序),并且后者小于等于
  3. self[end..] 中的每个元素。

此部分排序是不稳定的,意味着指定区间内的相等元素顺序可能被重排。指定区间外的元素顺序也可能被重排,但上述保证依然成立。

此部分排序是原地(不分配)的,最坏复杂度为 O(n + k * log(k)),其中 n 为切片长度,k 为指定区间长度。

实现细节请参阅 sort_unstable_by_key 的文档。

§Panics

当键提取函数的实现并非全序、或其本身 panic、或指定区间越界时,可能 panic。

§示例
[EXAMPLE]
1.49.0 · 源代码

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

对切片中的指定区间进行不稳定的选择排序,使区间内的某个元素被放到正确排序位置。

完成后,保证:

  1. self[..start] 中的每个元素都小于等于
  2. self[start..end] 中的每个元素(已部分排序),并且后者小于等于
  3. self[end..] 中的每个元素。

特别地,self[k] 等于排序后该位置的元素。

此排序是不稳定的。区间外的元素顺序也可能被重排,但上述保证依然成立。

此操作是原地(不分配)的;其最坏、平均与最佳时间复杂度均为 O(n);空间复杂度为 O(1)。

实现细节请参阅 select_nth_unstable_by 的文档。

§Panics

Ord 的实现并非全序、或其实现本身 panic、或指定区间越界时,可能 panic。

§示例
[EXAMPLE]
1.49.0 · 源代码

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,

使用给定的比较函数对切片中的指定区间进行不稳定的选择排序,使区间内某元素被放到正确排序位置。

完成后,保证:

  1. self[..start] 中的每个元素都小于等于
  2. self[start..end] 中的每个元素(已部分排序),并且后者小于等于
  3. self[end..] 中的每个元素。

特别地,self[k] 等于排序后该位置的元素。

此排序是不稳定的。区间外的元素顺序也可能被重排,但上述保证依然成立。

此操作是原地(不分配)的;其最坏、平均与最佳时间复杂度均为 O(n);空间复杂度为 O(1)。

§Panics

compare 不是全序、或其本身 panic、或指定区间越界时,可能 panic。

§示例
[EXAMPLE]
1.49.0 · 源代码

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,

使用给定的键提取函数对切片中的指定区间进行不稳定的选择排序。

完成后,保证:

  1. self[..start] 中的每个元素都小于等于
  2. self[start..end] 中的每个元素(已部分排序),并且后者小于等于
  3. self[end..] 中的每个元素。

特别地,self[k] 等于排序后该位置的元素。

此排序是不稳定的。区间外的元素顺序也可能被重排,但上述保证依然成立。

此操作是原地(不分配)的;其最坏、平均与最佳时间复杂度均为 O(n);空间复杂度为 O(1)。

§Panics

当键提取函数不是全序、或其本身 panic、或指定区间越界时,可能 panic。

§示例
[EXAMPLE]
源代码

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

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

依据 PartialEq trait 的实现,将切片中所有连续重复的元素移到末尾。

返回两个切片。第一个不含任何连续重复元素;第二个包含所有重复项(顺序未指定)。

若切片是已排序的,那么第一个返回的切片不含任何重复项。

§示例
[EXAMPLE]
源代码

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)

依据给定的相等性关系,将切片中除第一个外、连续的元素都移到末尾。

返回两个切片。第一个不含任何连续重复元素;第二个包含所有重复项(顺序未指定)。

same_bucket 函数接收切片中两个元素的引用,必须判断它们是否相等。两个元素按其切片中顺序的相反顺序传入,因此若 same_bucket(a, b) 返回 truea 会被移到切片末尾。

若切片是已排序的,那么第一个返回的切片不含任何重复项。

§示例
[EXAMPLE]
源代码

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)

将切片中除第一个外、连续的元素中具有相同键的元素移到末尾。

返回两个切片。第一个不含任何连续重复元素;第二个包含所有重复项(顺序未指定)。

若切片是已排序的,那么第一个返回的切片不含任何重复项。

§示例
[EXAMPLE]
1.26.0 · 源代码

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

将切片原地旋转,使得切片开头的 mid 个元素移到末尾,末尾的 self.len() - mid 个元素移到开头。

调用 rotate_left 后,原本索引为 mid 的元素将成为切片中的第一个元素。

§Panics

mid 大于切片长度则 panic。注意 mid == self.len() 不会 panic,是一次空操作旋转。

§复杂度

耗时与 self.len() 成线性。

§Examples
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
a.rotate_left(2);
assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);

Rotating a subslice:

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 · 源代码

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

将切片原地旋转,使得切片开头的 self.len() - k 个元素移到末尾,末尾的 k 个元素移到开头。

调用 rotate_right 后,原本索引为 self.len() - k 的元素将成为切片中的第一个元素。

§Panics

k 大于切片长度则 panic。注意 k == self.len() 不会 panic,是一次空操作旋转。

§复杂度

耗时与 self.len() 成线性。

§Examples
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
a.rotate_right(2);
assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);

Rotating a subslice:

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

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

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

将切片中的元素向左移动 N 个位置,返回从开头“掉出”的元素,并将 inserted 放到末尾。

等价地,你可以把 selfinserted 串接成一个长序列,然后把最左侧的 N 个返回,其余放回 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.

§Examples
#![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]);
源代码

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

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

将切片中的元素向右移动 N 个位置,返回从末尾“掉出”的元素,并将 inserted 放到开头。

等价地,你可以把 insertedself 串接成一个长序列,然后把最右侧的 N 个返回,其余放回 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.

§Examples
#![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 · 源代码

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

通过克隆 value 填充 self

§Examples
let mut buf = vec![0; 10];
buf.fill(1);
assert_eq!(buf, vec![1; 10]);
1.51.0 · 源代码

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

通过反复调用闭包所返回的元素填充 self

该方法使用闭包创建新值。若你更希望 Clone 一个给定的值,请使用 fill。若你希望借助 Default trait 来生成值,可以将 Default::default 作为参数传入。

§Examples
let mut buf = vec![1; 10];
buf.fill_with(Default::default);
assert_eq!(buf, vec![0; 10]);
1.7.0 · 源代码

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

src 中的元素拷贝到 self

src 的长度必须与 self 相同。

§Panics

若两个切片长度不同则 panic。

§示例

从一个切片中克隆两个元素到另一个切片:

[EXAMPLE]

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 from 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 · 源代码

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

src 中的元素拷贝到 self

两个切片必须等长。复杂度为 O(n)

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 from 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 · 源代码

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

使用 memmove 将切片的一部分拷贝到另一部分。

src 是要拷贝的源区间(在 self 内)。dest 是目标区间的起始索引(在 self 内),其长度与 src 相同。两个区间可以重叠。两区间的端点都必须小于等于 self.len()

§Panics

若任一区间超出切片末尾,或 src 的终点早于起点,则 panic。

§示例

在切片内拷贝四个字节:

[EXAMPLE]
1.27.0 · 源代码

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

将本切片与 other 切片中的元素互换。

两个切片必须等长。复杂度为 O(1)

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 from 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 · 源代码

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

将该切片转换为另一种类型的切片,并保证类型的对齐得到保持。

本方法将切片拆分为三段:前缀、类型正确对齐的中间切片以及后缀切片。在给定的对齐约束和元素大小下,中间段会被尽可能地拉长。

当输入元素 T 或输出元素 U 是零大小类型时,本方法无意义,会原样返回原切片,不做任何拆分。

§安全性

对返回的中间切片中的元素而言,本方法本质上等同于 transmute,因此 transmute::<T, U> 的所有常见注意事项在这里同样适用。

§示例

基本用法:

[EXAMPLE]
1.30.0 · 源代码

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

将该可变切片转换为另一种类型的可变切片,并保证类型的对齐得到保持。

本方法将切片拆分为三段:前缀、类型正确对齐的中间切片以及后缀切片。在给定的对齐约束和元素大小下,中间段会被尽可能地拉长。

当输入元素 T 或输出元素 U 是零大小类型时,本方法无意义,会原样返回原切片,不做任何拆分。

§安全性

对返回的中间切片中的元素而言,本方法本质上等同于 transmute,因此 transmute::<T, U> 的所有常见注意事项在这里同样适用。

§示例

基本用法:

[EXAMPLE]
源代码

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)

将切片拆分为一个前缀、一个对齐好的 SIMD 类型中间段以及一个后缀。

这是 slice::align_to 的安全包装,因此继承该方法的所有保证。

§Panics

若 SIMD 类型的大小与 LANES 倍标量类型大小不同,则 panic。

撰写本文档时,Simd<T, LANES> 上的 trait 约束使得这种情况不会发生——只支持 2 的幂次个 lane。未来这些约束若被解除,则可能在 LANES == 3 之类的情况下从此方法看到 panic。

§示例
[EXAMPLE]
源代码

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)

将可变切片拆分为一个可变前缀、一个对齐好的 SIMD 类型中间段以及一个可变后缀。

这是 slice::align_to_mut 的安全包装,因此继承该方法的所有保证。

这是 slice::as_simd 的可变版本;示例请参阅后者。

§Panics

若 SIMD 类型的大小与 LANES 倍标量类型大小不同,则 panic。

撰写本文档时,Simd<T, LANES> 上的 trait 约束使得这种情况不会发生——只支持 2 的幂次个 lane。未来这些约束若被解除,则可能在 LANES == 3 之类的情况下从此方法看到 panic。

1.82.0 · 源代码

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

检查切片中的元素是否已排序。

也就是说,对每个元素 a 及其后继元素 b,必须满足 a <= b。若切片恰好产出零或一个元素,则返回 true

注意,若 Self::Item 只实现了 PartialOrd 而未实现 Ord,那么按上述定义,一旦出现任意两个相邻项不可比较的情况,本函数就会返回 false

§示例
[EXAMPLE]
1.82.0 · 源代码

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

使用给定的比较函数检查切片中的元素是否已排序。

本函数不使用 PartialOrd::partial_cmp,而是使用给定的 compare 函数来判断两个元素是否可视为处于已排序顺序中。

§示例
[EXAMPLE]
1.82.0 · 源代码

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

使用给定的键提取函数检查切片中的元素是否已排序。

本函数并不直接比较切片元素,而是按 f 所决定的键进行比较。除此之外与 is_sorted 等价;更多信息请参阅该方法的文档。

§示例
[EXAMPLE]
1.52.0 · 源代码

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

依据给定的谓词返回切分点的索引(即第二个分区的首元素索引)。

切片假定已按给定谓词切分,意味着所有谓词返回 true 的元素位于切片开头,所有返回 false 的元素位于切片末尾。例如,[7, 15, 3, 5, 4, 12, 6] 在谓词 x % 2 != 0 下就是切分好的(所有奇数在前、所有偶数在后)。

若切片并未真正切分,则返回结果是未指定且无意义的,因为本方法本质上是一种二分查找。

另请参阅 binary_searchbinary_search_bybinary_search_by_key

§示例
[EXAMPLE]

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 · 源代码

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

移除对应给定范围的子切片,并返回它的引用。

若给定范围越界,则返回 None 且不修改切片。

注意,本方法只接受单边区间(如 2....6),不接受 2..6

§示例

切下切片的前三个元素:

[EXAMPLE]

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 · 源代码

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

移除对应给定范围的子切片,并返回它的可变引用。

若给定范围越界,则返回 None 且不修改切片。

注意,本方法只接受单边区间(如 2....6),不接受 2..6

§示例

切下切片的前三个元素:

[EXAMPLE]

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 · 源代码

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

移除切片的第一个元素并返回它的引用。

若切片为空则返回 None

§示例
[EXAMPLE]
1.87.0 · 源代码

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

移除切片的第一个元素并返回它的可变引用。

若切片为空则返回 None

§示例
[EXAMPLE]
1.87.0 · 源代码

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

移除切片的最后一个元素并返回它的引用。

若切片为空则返回 None

§示例
[EXAMPLE]
1.87.0 · 源代码

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

移除切片的最后一个元素并返回它的可变引用。

若切片为空则返回 None

§示例
[EXAMPLE]
1.86.0 · 源代码

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

一次性返回对多个索引的可变引用,不做任何检查。

索引可以是 usizeRangeRangeInclusive。注意本方法接收的是一个数组,因此所有索引类型必须一致;若传入的是 usize 数组,则返回的是对单个元素的可变引用数组;若传入的是区间数组,则返回的是对子切片的可变引用数组。

如需安全版本,请参阅 get_disjoint_mut

§安全性

即便不使用所得到的引用,使用重叠或越界的索引调用本方法也属于未定义行为

§示例
[EXAMPLE]
1.86.0 · 源代码

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

一次性返回对多个索引的可变引用。

索引可以是 usizeRangeRangeInclusive。注意本方法接收的是一个数组,因此所有索引类型必须一致;若传入的是 usize 数组,则返回的是对单个元素的可变引用数组;若传入的是区间数组,则返回的是对子切片的可变引用数组。

若任一索引越界或存在重叠索引则返回错误。空区间若位于另一区间的开头或末尾不被视为重叠,但位于中间则视为重叠。

本方法以 O(n²) 的开销检查索引之间没有重叠,因此传入大量索引时请注意。

§示例
[EXAMPLE]
1.94.0 · 源代码

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

返回某元素引用所指向的索引。

element 并不指向切片中某个元素的起点,则返回 None

本方法对于扩展诸如 slice::split 这样的切片迭代器非常有用。

注意本方法使用了指针算术,并不比较元素。若要通过比较查找元素索引,请改用 .iter().position()

§Panics

T 是零大小类型则 panic。

§示例

基本用法:

[EXAMPLE]

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
源代码

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

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

返回某子切片所对应的索引区间。

subslice 不指向切片内部,或未与切片中元素对齐,则返回 None

本方法不比较元素,而是找出 subslice 在切片中所源自的位置。若要通过比较查找子切片的索引,请改用 .windows().position()

本方法对于扩展诸如 slice::split 这样的切片迭代器非常有用。

subslice 长度为 0 并指向另一段独立切片的开头或结尾,则可能返回误报(即 Some(0..0)Some(self.len()..self.len()))。

§Panics

T 是零大小类型则 panic。

§示例

基本用法:

[EXAMPLE]
源代码

pub fn as_slice(&self) -> &[T]

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

返回同一切片 &[T]

直接在 &[T] 上调用此方法属于冗余操作,但其有助于把其他“容器”类型解引用为切片,例如 Box<[T]>Arc<[T]>

源代码

pub fn as_mut_slice(&mut self) -> &mut [T]

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

返回同一可变切片 &mut [T]

直接在 &mut [T] 上调用此方法属于冗余操作,但其有助于把其他“容器”类型解引用为切片,例如 Box<[T]>MutexGuard<[T]>

1.79.0 · 源代码

pub fn utf8_chunks(&self) -> Utf8Chunks<'_>

在此切片上创建一个迭代器,遍历连续的合法 UTF-8 区间及其之间的非 UTF-8 片段。

迭代器所产出项的文档请参阅 Utf8Chunk

§示例

本函数可将任意(但主要是 UTF-8 的)字节格式化为形如 c"..." 的 C 字符串字面量。

[EXAMPLE]
1.0.0 · 源代码

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

对切片进行原地排序。

此排序是稳定的(即不重排相等元素的相对顺序),最坏情况的时间复杂度为 O(n * log(n)),空间复杂度为 O(1)

1.0.0 · 源代码

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

使用给定的比较函数对切片进行原地稳定排序。

此排序是稳定的,最坏情况时间复杂度为 O(n * log(n)),空间复杂度为 O(1)

1.7.0 · 源代码

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

使用从元素派生的键对切片进行原地稳定排序。

1.34.0 · 源代码

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

使用从元素派生的键对切片进行原地稳定排序,键只计算一次。

1.0.0 · 源代码

pub fn to_vec(&self) -> Vec<T>
where T: Clone,

self 拷贝到一个新的 Vec 中。

§示例
let s = [10, 40, 30];
let x = s.to_vec();
// Here, `s` and `x` can be modified independently.
源代码

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)

使用指定分配器,将 self 拷贝到一个新的 Vec 中。

§示例
#![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 · 源代码

pub fn repeat(&self, n: usize) -> Vec<T>
where T: Copy,

创建一个长度为 n 的向量,其中每个元素都是给定值的一份拷贝。

A panic upon overflow:

// this will panic at runtime
b"0123456789abcdef".repeat(usize::MAX);
1.0.0 · 源代码

pub fn concat<Item>(&self) -> <[T] as Concat<Item>>::Output
where [T]: Concat<Item>, Item: ?Sized,

T 类型的切片扁平化为单个值 Self::Output

§示例
assert_eq!(["hello", "world"].concat(), "helloworld");
assert_eq!([[1, 2], [3, 4]].concat(), [1, 2, 3, 4]);
1.3.0 · 源代码

pub fn join<Separator>( &self, sep: Separator, ) -> <[T] as Join<Separator>>::Output
where [T]: Join<Separator>,

T 类型的切片扁平化为单个值 Self::Output,并在每两个相邻元素之间插入给定的分隔符。

§示例
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 · 源代码

pub fn connect<Separator>( &self, sep: Separator, ) -> <[T] as Join<Separator>>::Output
where [T]: Join<Separator>,

👎Deprecated since 1.3.0: renamed to join

T 类型的切片扁平化为单个值 Self::Output,并在每两个相邻元素之间插入给定的分隔符。

§示例
assert_eq!(["hello", "world"].connect(" "), "hello world");
assert_eq!([[1, 2], [3, 4]].connect(&0), [1, 2, 0, 3, 4]);
1.23.0 · 源代码

pub fn to_ascii_uppercase(&self) -> Vec<u8>

返回一个包含本切片副本的向量,其中每个字节都被映射为对应的 ASCII 大写形式。

ASCII 字母 az 会被映射为 AZ,但非 ASCII 字母保持不变。

若希望就地大写化,请使用 make_ascii_uppercase

1.23.0 · 源代码

pub fn to_ascii_lowercase(&self) -> Vec<u8>

返回一个包含本切片副本的向量,其中每个字节都被映射为对应的 ASCII 小写形式。

ASCII 字母 AZ 会被映射为 az,但非 ASCII 字母保持不变。

若希望就地小写化,请使用 make_ascii_lowercase

trait 实现§

源代码§

impl Clone for ConnectionId

源代码§

fn clone(&self) -> ConnectionId

返回值的副本。 更多信息
1.0.0 · 源代码§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. 更多信息
源代码§

impl Debug for ConnectionId

源代码§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

使用给定的格式化器格式化此值。 更多信息
源代码§

impl Deref for ConnectionId

源代码§

type Target = [u8]

解引用后得到的类型。
源代码§

fn deref(&self) -> &[u8]

解引用此值。
源代码§

impl DerefMut for ConnectionId

源代码§

fn deref_mut(&mut self) -> &mut [u8]

以可变方式解引用此值。
源代码§

impl Display for ConnectionId

源代码§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

使用给定的格式化器格式化此值。 更多信息
源代码§

impl Hash for ConnectionId

源代码§

fn hash<__H>(&self, state: &mut __H)
where __H: Hasher,

Feeds this value into the given Hasher. 更多信息
1.3.0 · 源代码§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. 更多信息
源代码§

impl Ord for ConnectionId

源代码§

fn cmp(&self, other: &ConnectionId) -> Ordering

This method returns an Ordering between self and other. 更多信息
1.21.0 · 源代码§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. 更多信息
1.21.0 · 源代码§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. 更多信息
1.50.0 · 源代码§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. 更多信息
源代码§

impl PartialEq for ConnectionId

源代码§

fn eq(&self, other: &ConnectionId) -> bool

测试 selfother 值是否相等,供 == 运算符使用。
1.0.0 · 源代码§

fn ne(&self, other: &Rhs) -> bool

测试 != 运算符。默认实现几乎总是够用,除非有非常充分的理由,否则不应被覆盖。
源代码§

impl PartialOrd for ConnectionId

源代码§

fn partial_cmp(&self, other: &ConnectionId) -> Option<Ordering>

若存在,此方法返回 selfother 值之间的排序关系。 更多信息
1.0.0 · 源代码§

fn lt(&self, other: &Rhs) -> bool

测试小于(针对 selfother),供 < 运算符使用。 更多信息
1.0.0 · 源代码§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. 更多信息
1.0.0 · 源代码§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. 更多信息
1.0.0 · 源代码§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. 更多信息
源代码§

impl Copy for ConnectionId

源代码§

impl Eq for ConnectionId

源代码§

impl StructuralPartialEq for ConnectionId

自动 trait 实现§

§

impl Freeze for ConnectionId

§

impl RefUnwindSafe for ConnectionId

§

impl Send for ConnectionId

§

impl Sync for ConnectionId

§

impl Unpin for ConnectionId

§

impl UnsafeUnpin for ConnectionId

§

impl UnwindSafe for ConnectionId

blanket 实现§

源代码§

impl<T> Any for T
where T: 'static + ?Sized,

源代码§

fn type_id(&self) -> TypeId

Gets the TypeId of self. 更多信息
源代码§

impl<T> Borrow<T> for T
where T: ?Sized,

源代码§

fn borrow(&self) -> &T

Immutably borrows from an owned value. 更多信息
源代码§

impl<T> BorrowMut<T> for T
where T: ?Sized,

源代码§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. 更多信息
源代码§

impl<T> CloneToUninit for T
where T: Clone,

源代码§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 更多信息
源代码§

impl<T> From<T> for T

源代码§

fn from(t: T) -> T

原样返回该参数。

源代码§

impl<T> Instrument for T

源代码§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. 更多信息
源代码§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. 更多信息
源代码§

impl<T, U> Into<U> for T
where U: From<T>,

源代码§

fn into(self) -> U

调用 U::from(self)

也就是说,此转换行为完全由 From<T> for U 的实现决定。

源代码§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

源代码§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
源代码§

impl<T> ToOwned for T
where T: Clone,

源代码§

type Owned = T

获得所有权后的类型。
源代码§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. 更多信息
源代码§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. 更多信息
源代码§

impl<T> ToString for T
where T: Display + ?Sized,

源代码§

fn to_string(&self) -> String

Converts the given value to a String. 更多信息
源代码§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

源代码§

type Error = Infallible

转换出错时返回的类型。
源代码§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

执行转换。
源代码§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

源代码§

type Error = <U as TryFrom<T>>::Error

转换出错时返回的类型。
源代码§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

执行转换。
源代码§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

源代码§

fn vzip(self) -> V

源代码§

impl<T> WithSubscriber for T

源代码§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. 更多信息
源代码§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. 更多信息
源代码§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

源代码§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

源代码§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,