Slice and vector operations
Quick answer
A slice gives access to a contiguous range without owning it. Use slices in functions that only need to read or edit existing elements; use a vector when length must change.
Choose the smallest interface
&[T] accepts slices from arrays and vectors. &mut [T] supports in-place operations such as reverse. retain on Vec keeps elements matching a predicate (a function returning bool); the closure |n| ... is a short anonymous function, covered in detail later.
fn main() { let mut v = vec![1, 2, 3, 4]; v[1..3].reverse(); println!("{v:?}");}Expected stdout (not executed):
[1, 3, 2, 4]Only indices one and two change.
fn main() { let mut scores = vec![9, -1, 20, 25]; scores.retain(|n| (0..=20).contains(n)); println!("{scores:?}");}Expected stdout (not executed):
[9, 20]The vector shrinks while the order of retained elements stays the same.
Common mistake
A mutable slice cannot add new elements or change its own length.
Try it yourself
Write a function taking &mut [i32] that reverses its input; call it with an array and a Vec.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Slice and vector operations — practice quiz
Choose one answer per question, then review the explanation.
What does `reverse` on a mutable slice change?
Given `v.retain(|n| *n > 0)`, what remains of [-2, 3, 0, 4]?
Can a function accepting `&[i32]` read part of a Vec<i32>?