slice

Common methods on [T]: first, last, get, split_at, windows, chunks, sort, binary_search, and copy_from_slice, including bounds and sort stability.

主题页正文目前为英文。

A slice [T] is the unsized view of a contiguous sequence. Arrays and Vec<T> coerce or dereference to [T], so most of the methods in this page are the ones you call after let s = &values[..] or by auto-deref from a Vec. The Vec page already covers indexing versus get, push, pop, remove, and swap_remove. This page starts from the slice itself: views, bounds, sorting, and copying into an existing buffer.

A string slice str is UTF-8 text, not a [char]. Mid-character byte indexes and is_char_boundary stay on the str page. Examples were compiled with rustc 1.90.0 and --edition=2024.

Examples were compiled with rustc 1.90.0 using --edition=2024 and run as a plain binary. See the Rust 1.90.0 documentation for the complete API.

Rust reference overview →

API index

APISummary
[T]::first, last, get, split_at, windows, chunksRead ends and optional indexes, split a slice into two borrows, and iterate overlapping windows or non-overlapping chunks. Several of these panic on an invalid size or midpoint.
[T]::sort, sort_by_key, binary_search, copy_from_sliceSort a slice in place, search a sorted slice, or copy elements into a destination of the same length.

Bounds, split_at, windows, and chunks

first and last return Option. get also returns Option, including for an out-of-range index. Direct indexing of a slice panics when the index is out of range, which the Vec page already demonstrates. split_at(mid) returns two borrows that together cover the original slice. It is valid when mid == len, and it panics when mid > len. On rustc 1.90.0, split_at_checked is the Option-returning alternative.

windows(size) and chunks(chunk_size) return iterators of subslices. windows(0) and chunks(0) panic. The last chunk may be shorter than the requested size; chunks_exact leaves a remainder instead.

[T]::first, last, get, split_at, windows, chunks

pub const fn first(&self) -> Option<&T>
pub const fn last(&self) -> Option<&T>
pub const fn get<I>(&self, index: I) -> Option<&I::Output>
pub const fn split_at(&self, mid: usize) -> (&[T], &[T])
pub const fn windows(&self, size: usize) -> Windows<'_, T>
pub fn chunks(&self, chunk_size: usize) -> Chunks<'_, T>

Read ends and optional indexes, split a slice into two borrows, and iterate overlapping windows or non-overlapping chunks. Several of these panic on an invalid size or midpoint.

ParameterDescription
indexA slice index or range for get. Out of range yields None rather than a panic. The official signature is generic over SliceIndex<[T]>; I::Output is a shortened form of that associated type.
midThe split point. 0 and len are valid. mid greater than len panics in split_at.
size / chunk_sizeThe window or chunk length. Zero panics. A chunk may be shorter at the end of the slice.

Returns: first, last, and get return Option. split_at returns two shared borrows of the same slice. windows and chunks return iterator types from the standard library.

  • The two sides of split_at, and each window or chunk, borrow the original slice. You cannot hold a mutable borrow of one part and another overlapping borrow of the same slice at the same time.
  • split_at_mut and chunks_mut exist for exclusive access. The borrow checker still forbids overlapping mutable views.
  • Vec indexing versus get, and the panic from values[9], stay on the Vec page.
rust
fn main() {
    let values = [10, 20, 30, 40];
    let s = &values[..];
    println!("first={:?} last={:?} get9={:?}", s.first(), s.last(), s.get(9));
    let (head, tail) = s.split_at(2);
    println!("head={head:?} tail={tail:?}");
    std::panic::set_hook(Box::new(|_| {}));
    let split_panic = std::panic::catch_unwind(|| {
        let _ = values.split_at(5);
    })
    .is_err();
    let windows_panic = std::panic::catch_unwind(|| {
        let _ = values.windows(0).next();
    })
    .is_err();
    println!("split_at5 panicked={split_panic} windows0 panicked={windows_panic}");
    let windows: Vec<_> = values.windows(2).collect();
    let chunks: Vec<_> = values.chunks(3).collect();
    println!("windows={windows:?}");
    println!("chunks={chunks:?}");
}

Expected output

first=Some(10) last=Some(40) get9=None
head=[10, 20] tail=[30, 40]
split_at5 panicked=true windows0 panicked=true
windows=[[10, 20], [20, 30], [30, 40]]
chunks=[[10, 20, 30], [40]]

Related: Vec indexing versus get, str byte indexes and char boundaries, Iterator consumers

Official documentation →

sort, binary_search, and copy_from_slice

sort is a stable sort: elements that compare equal keep their relative order. sort_unstable may reorder equal elements, and this reference does not treat any particular equal-key order from it as a guarantee. Both require T: Ord. f64 does not implement Ord; a total order for floats is on the cmp page via total_cmp.

binary_search requires the slice to already be sorted by the same order. copy_from_slice copies from a source of equal length and requires T: Copy. A length mismatch panics. Use clone_from_slice when the elements are Clone but not Copy.

[T]::sort, sort_by_key, binary_search, copy_from_slice

pub fn sort(&mut self)
    where
        T: Ord
pub fn sort_by_key<K, F>(&mut self, f: F)
    where
        F: FnMut(&T) -> K,
        K: Ord
pub fn binary_search(&self, x: &T) -> Result<usize, usize>
    where
        T: Ord
pub fn copy_from_slice(&mut self, src: &[T])
    where
        T: Copy

Sort a slice in place, search a sorted slice, or copy elements into a destination of the same length.

ParameterDescription
fA key function for sort_by_key. The sort is stable with respect to that key.
xThe value to search for in a slice that is already sorted.
srcA source slice whose length must equal self.len(), or copy_from_slice panics.

Returns: sort and copy_from_slice return (). binary_search returns Ok(index) when a matching element is found, or Err(index) with the insertion point.

  • In the example, sort_by_key keeps b, then a, then c when two items share the key 2. That is the insertion order among equals, which stability promises.
  • sort_unstable and sort_unstable_by_key may be faster, but equal keys can move. Do not assert a particular order among equals after an unstable sort.
  • binary_search on an unsorted slice is not a logic error the compiler can catch; the result is simply not meaningful.
rust
fn main() {
    let mut unique = [3, 1, 2, 1];
    unique.sort();
    println!("sort={unique:?}");
    #[allow(dead_code)]
    #[derive(Debug, Clone)]
    struct Item {
        k: i32,
        id: char,
    }
    let mut items = [
        Item { k: 2, id: 'a' },
        Item { k: 1, id: 'b' },
        Item { k: 2, id: 'c' },
    ];
    items.sort_by_key(|item| item.k);
    println!("stable={items:?}");
    println!("search={:?}", [1, 2, 4, 5].binary_search(&4));
    let mut dest = [0, 0, 0];
    dest.copy_from_slice(&[7, 8, 9]);
    println!("copied={dest:?}");
}

Expected output

sort=[1, 1, 2, 3]
stable=[Item { k: 1, id: 'b' }, Item { k: 2, id: 'a' }, Item { k: 2, id: 'c' }]
search=Ok(2)
copied=[7, 8, 9]

Related: Ord, PartialOrd, and total_cmp, Official slice sort

Official documentation →