Rust Tutorial: Slices
View parts of arrays and strings without copying. Understanding &[T] and &str.
Views into collections
A slice is a reference to a contiguous run of elements. It lets you work with part of a collection without copying it.
What you'll learn in this Rust slices tutorial
This interactive Rust tutorial has 8 hands-on exercises. Estimated time: 15 minutes.
- String slices — A string slice `&str` references part of a String. `&s[start..end]` creates it.
- Array slices — Slices work on any contiguous sequence. The type is `&[T]`.
- Functions accepting slices — Use `&[T]` as the parameter type — it accepts any contiguous sequence.
- Iterating a slice — `for item in slice` iterates over references. Use `&` in the pattern to destructure.
- Mutable slices — A mutable slice `&mut [T]` lets you modify elements in place.
- Slice methods — Slices have useful built-in methods.
- Splitting slices — `split_at(n)` divides a slice into two at index n.
- windows and chunks — `windows(n)` gives overlapping windows; `chunks(n)` gives non-overlapping groups.
Rust Slices concepts covered
- Views into collections