Sub topic 3
Creating slices with ranges
This chapter shows how range expressions turn an array or vector into a slice. It assumes you know what a slice is (&[T], a borrowed view of contiguous elements) and how arrays and Vec<T> store their elements. It also assumes basic borrowing. The next chapter covers what happens when a range is out of bounds in more detail. This chapter only introduces the panics.
The shape of the syntax
You create a slice by indexing a collection with a range and then borrowing the result:
fn main() {
let a = [10, 20, 30, 40, 50];
println!("{:?}", &a[1..4]); // [20, 30, 40]
println!("{:?}", &a[..2]); // [10, 20]
println!("{:?}", &a[3..]); // [40, 50]
println!("{:?}", &a[..]); // [10, 20, 30, 40, 50]
println!("{:?}", &a[1..=3]); // [20, 30, 40]
println!("{:?}", &a[..=1]); // [10, 20]
}Each of these forms is a different range type from std::ops. All of them produce a &[i32].
| Syntax | Type | Elements selected |
|---|---|---|
| `a[start..end]` | `Range<usize>` | from `start` up to, but not including, `end` |
| `a[start..]` | `RangeFrom<usize>` | from `start` to the end |
| `a[..end]` | `RangeTo<usize>` | from the beginning up to, but not including, `end` |
| `a[..]` | `RangeFull` | everything |
| `a[start..=end]` | `RangeInclusive<usize>` | from `start` through `end` |
| `a[..=end]` | `RangeToInclusive<usize>` | from the beginning through `end` |
A range literal is an ordinary expression that builds a value of one of these types. The Index implementation for slices accepts any of them, because they all implement the SliceIndex trait.
Correction: the diagram must be a diagram fence, so it appears here in its proper form.
Half-open ranges and the length rule
The start..end form is half-open. It includes start and excludes end. This gives you two useful properties.
- The length of the slice is
end - start. Here,1..4selects 3 elements. - Adjacent ranges share a boundary without overlapping or leaving a gap.
The second property makes it easy to cut a slice into two pieces at one index:
fn main() {
let a = [10, 20, 30, 40, 50];
let mid = 2;
let head = &a[..mid];
let tail = &a[mid..];
println!("{:?} {:?}", head, tail); // [10, 20] [30, 40, 50]
println!("{}", head.len() + tail.len() == a.len()); // true
}The inclusive form start..=end includes end, so its length is end - start + 1. Use it when the end index is the natural way to state the problem, for example "elements 1 through 3". Prefer the half-open form when you compute the end from a length, since start + len needs no - 1 adjustment.
The leading `&` is required
Indexing with a range names a place whose size the compiler cannot know. a[1..4] has type [i32], a slice with no fixed length. You cannot store an unsized value in a local variable, so let s = a[1..4]; is a compile error. You must borrow it with &a[1..4], or &mut a[1..4] if you need to change the elements. The reference then carries the length at run time. The fat-pointer chapter explains this in detail.
Slicing arrays, vectors, and other slices
The same syntax works on arrays, Vec<T>, and slices. For a Vec, indexing goes through the vector's dereference to a slice, so the result is the same type:
fn main() {
let v = vec![1, 2, 3, 4, 5, 6];
let s: &[i32] = &v[2..5];
println!("{:?}", s); // [3, 4, 5]
let t = &s[1..];
println!("{:?}", t); // [4, 5]
println!("{}", t[0]); // 4
}Notice that indices are always relative to the thing you are indexing. s[1..] starts at the second element of s, which is v[3]. A slice does not remember where it came from, so t[0] is the first element of t.
An empty slice is valid and common. A range whose start equals its end gives zero elements, and a start equal to the length is allowed:
fn main() {
let a = [10, 20, 30, 40, 50];
println!("{:?}", &a[2..2]); // []
println!("{:?}", &a[5..]); // []
println!("{:?}", &a[..0]); // []
}This matters for loops that shrink a slice from the front. They can run until the slice is empty without a special case for the last step.
Index types: `usize` only
Range bounds must be usize. Rust has no negative indices, so there is no a[..-1]. If your bound is some other integer type, convert it explicitly:
fn main() {
let a = [10, 20, 30, 40, 50];
let i: i32 = 2;
let start = i as usize;
println!("{:?}", &a[start..]); // [30, 40, 50]
}To get "everything except the last element", compute it from the length: &a[..a.len() - 1]. This underflows and panics in debug builds when the length is 0, because usize cannot go below zero. Check for emptiness first, or use a method such as split_last (covered in a later chapter).
Ranges are values
Because a range is a value, you can build one, pass it around, and use it later. Range<usize> is not Copy, so using it to index moves it. Clone it if you still need it:
use std::ops::Range;
fn window(data: &[i32], r: Range<usize>) -> &[i32] {
&data[r]
}
fn main() {
let a = [10, 20, 30, 40, 50];
let r = 1..4;
let s = &a[r.clone()];
println!("{:?} {:?}", r, s); // 1..4 [20, 30, 40]
println!("{:?}", window(&a, 0..2)); // [10, 20]
}The returned slice has the lifetime of data, not of the range. The elision rules tie the output lifetime to the only reference parameter, and r is not a reference.
When the range does not fit
Slicing with [] checks the range at run time and panics if it is invalid. There are two ways to be invalid.
- The start is greater than the end, as in
&a[3..2]. - The end is greater than the length, as in
&a[..6]on a 5-element array. For..=, the end index itself must be less than the length. That is why&a[..=5]also panics on a 5-element array.
The panic message names the offending index and the length. A start beyond the length, such as &a[6..], also panics. A start exactly equal to the length is fine and yields an empty slice.
A common defensive idiom is to clamp the bound before slicing:
fn first_n(data: &[i32], n: usize) -> &[i32] {
&data[..n.min(data.len())]
}
fn main() {
let a = [10, 20, 30, 40, 50];
println!("{:?}", first_n(&a, 3)); // [10, 20, 30]
println!("{:?}", first_n(&a, 99)); // [10, 20, 30, 40, 50]
}Clamping is right when "as many as available" is the behavior you want. If a bad range means a bug in your program, the panic is the correct outcome. If a bad range comes from outside input, use get, which returns an Option instead of panicking. The next chapter covers it.
Common mistakes
- Forgetting
&.let s = a[1..3];fails because the slice is unsized. Write&a[1..3]. - Off-by-one with
..=.&a[1..=3]has three elements, the same as&a[1..4]. Mixing the two forms in one expression is a frequent source of bugs. - Reading indices as absolute. After
let t = &s[1..], positions intstart again at 0. - Using a signed integer.
a[i..]withi: i32does not compile, sincei32is not a valid slice index. Convert deliberately and check the sign first. - Computing
len - kwithout checking. Iflen < k, the subtraction underflows. Usesaturating_subwhen zero is an acceptable floor:&a[a.len().saturating_sub(2)..]gives the last two elements, or all of them if there are fewer.
Summary of the working model
A range expression picks a start and an end. Indexing a contiguous collection with it names that sub-region, and & or &mut turns the region into a slice reference. The six range forms differ only in which bounds are left open and whether the end is included. The check against the real length happens at run time, and a bad range panics.
Exercise
For let a = [10, 20, 30, 40, 50];, what do &a[3..=3], &a[5..5], and &a[5..=5] evaluate to?
Show answer
&a[3..=3] is [40], one element. &a[5..5] is an empty slice, because a start equal to the length is allowed and the range selects nothing. &a[5..=5] panics, because the inclusive end index 5 is not less than the length 5.
Exercise
Write a function last_two(s: &[i32]) -> &[i32] that returns the last two elements of s, or all of s if it has fewer than two elements. It must not panic for any input.
Show answer
fn lasttwo(s: &[i32]) -> &[i32] {
&s[s.len().saturatingsub(2)..]
}
For a length of 5 the start is 3, giving the last two elements. For a length of 1 or 0, saturating_sub returns 0, so the slice is the whole input, and an empty input gives an empty slice.