Sub topic 3
Creating slices with ranges
This chapter assumes you know basic Rust syntax, ownership, references, and how arrays and Vec<T> store their elements. It covers the syntax for creating a slice. Handling bad indices and string slices comes in later chapters.
Borrowing a range
A slice is a borrowed view of consecutive elements. You create one by indexing an array or vector with a range and taking a reference to the result.
fn main() {
let a = [10, 20, 30, 40, 50];
let s = &a[1..4];
println!("{:?} len={}", s, s.len());
}This prints [20, 30, 40] len=3. The variable s has type &[i32]. It points into a and copies nothing.
The range 1..4 is half-open. It includes index 1 and excludes index 4, so the length is end - start.
The range forms
You can leave out either end, and you can make the end inclusive.
| Syntax | Meaning | Result for `[10, 20, 30, 40, 50]` |
|---|---|---|
| `a[1..4]` | start 1, end 4 (excluded) | `[20, 30, 40]` |
| `a[..2]` | from the beginning to 2 (excluded) | `[10, 20]` |
| `a[3..]` | from 3 to the end | `[40, 50]` |
| `a[1..=3]` | start 1, end 3 (included) | `[20, 30, 40]` |
| `a[..=1]` | from the beginning to 1 (included) | `[10, 20]` |
| `a[..]` | the whole thing | `[10, 20, 30, 40, 50]` |
fn main() {
let a = [10, 20, 30, 40, 50];
println!("{:?}", &a[1..4]);
println!("{:?}", &a[..2]);
println!("{:?}", &a[3..]);
println!("{:?}", &a[1..=3]);
println!("{:?}", &a[..=1]);
println!("{:?}", &a[..]);
println!("{:?}", &a[2..2]);
}The last line prints []. A range whose start equals its end gives a valid empty slice. The a[..] form is useful for turning a whole array or Vec into a slice explicitly.
Slicing vectors and using variables
Vectors work the same way. The bounds can be any expression of type usize.
fn main() {
let v = vec![1, 2, 3, 4, 5, 6];
let mid = v.len() / 2;
let (front, back) = (&v[..mid], &v[mid..]);
println!("{:?} {:?}", front, back);
}This prints [1, 2, 3] [4, 5, 6]. Splitting at the same index mid gives two pieces that do not overlap and leave nothing out.
A range is also an ordinary value. You can store it and use it later:
fn main() {
let v = vec![1, 2, 3, 4, 5];
let window = 1..3;
println!("{:?}", &v[window]);
}This prints [2, 3].
Why the `&` is required
The expression a[1..4] has type [i32], a sequence whose length is not known at compile time. Rust cannot store a value like that in a variable or pass it by value. You must put it behind a reference.
fn main() {
let a = [1, 2, 3];
let s = a[0..2]; // error: the size for values of type `[i32]` cannot be known
println!("{:?}", s);
}The fix is let s = &a[0..2];. A later chapter explains how the reference stores both a pointer and a length.
Common errors
- Index type. Range bounds must be
usize. Using ani32oru32variable gives a type error. Convert it withas usizeorusize::try_from. - Off-by-one with
..=.a[1..=3]has three elements, anda[1..3]has two. Choose the form that matches how you think about the end. - Out-of-range bounds. If the start is greater than the end, or the end is greater than the length, the program panics at run time. The compiler does not catch this when the values are only known at run time. The next chapter shows how to handle this case.
- Underflow in the bounds. Writing
&v[..v.len() - 1]on an empty vector subtracts from0usize. This panics in debug builds, and it wraps in release builds, which then produces an out-of-range slice.
Exercise
Given let v = vec![5, 6, 7, 8, 9];, what do &v[1..=3] and &v[3..] print with {:?}, and what is the length of &v[2..2]?
Show answer
&v[1..=3] prints [6, 7, 8], because the end index 3 is included. &v[3..] prints [8, 9]. The slice &v[2..2] is empty, so its length is 0.