By the end of this lesson
Borrow a contiguous part of a sequence without copying it.
Before you start
- Rust 1.90.0 or later, a terminal and a plain-text editor. Examples were tested with Rust 1.90.0, Edition 2024 on Linux.
- Complete lesson 12, or be comfortable explaining and running its examples.
Three words to know
- Slice
- A borrowed view of contiguous elements.
- Boundary
- A valid start or end position.
- Lifetime of a borrow
- How long referenced data must remain valid.
1. Understand the idea
&items[start..end] borrows a range without allocating another vector. The end is excluded. The source collection must outlive the slice’s use. String slices have an additional UTF-8 requirement: indices must fall on character boundaries. get can report invalid ranges safely rather than panicking. Prefer split_whitespace or another text-aware operation when that is what your task means.
2. Save, run and observe
Save this complete program as lesson.rs in a fresh practice folder. It replaces that lesson file only; keep earlier examples separately. Compile it with rustc, then run the executable. Rust source goes in the editor; rustc and cargo commands go in the terminal.
fn main() {
let values = [10, 20, 30, 40];
let middle = &values[1..3];
println!("{middle:?}");
println!("valid_boundary={}", "é".get(..1).is_some());
}
What you should see · example output
[20, 30] valid_boundary=false
rustc --edition=2024 lesson.rs -o lesson
./lesson3. Explain the result
Debug formatting :? prints the small integer slice. The byte offset 1 falls inside the two-byte encoding of é, so get(..1) returns None. This is different from a missing array position but is handled using the same Option pattern.
YOUR TURN
A small check before you continue
What does &values[..2] contain?
Show a suggested answer
The first two elements, 10 and 20. The end position 2 is excluded.
Sources and scope
Documentation and examples reviewed 2026-10-18. Provider screens, package versions and output wording can differ. Examples show expected outcomes; they are not a claim that OpenViST connected to your server or verified your setup.
