Slices
| Slice a vector | |
| Length | |
| Split at | |
| Windows and chunks |
Slice a vector
A slice is a borrowed view into part of a vector or array. A range inside brackets selects the start and end positions:
let v = vec![1, 2, 3, 4];
let s = &v[0..2];
Length
Both vectors and slices report size with len and emptiness with is_empty. Both calls borrow and never move data:
let v = vec![1, 2, 3];
let n = v.len();
let empty = v.is_empty();
Split at
Split at divides one slice into two parts at one index. The left part holds the start and the right part holds the rest:
let v = vec![1, 2, 3, 4];
let (a, b) = v.split_at(2);
Windows and chunks
Windows slides a small view across a slice, while chunks cuts it into fixed blocks. Both are ideal for grouped processing:
let v = vec![1, 2, 3, 4];
for w in v.windows(2) {
println!("{}", w.len());
}
Next: if and else
Article author: Arthur Isaev