[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.
| Parameter | Description |
|---|---|
index | A 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. |
mid | The split point. 0 and len are valid. mid greater than len panics in split_at. |
size / chunk_size | The 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.
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