Borrow exactly the part you need.
Use borrowed ranges without confusing bytes and characters.
01 Understand the contract
A slice &[T] describes a contiguous range using a pointer and a length. It borrows the elements rather than copying them. A string slice &str additionally guarantees valid UTF-8. String range indexes refer to bytes and must fall on UTF-8 character boundaries. get on a string range returns None for invalid bounds or a split inside a code point, while direct indexing by such a range panics. Work with chars for scalar iteration and a Unicode-aware crate when your product needs grapheme segmentation.
02 Make it concrete
This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.
fn main() {
let values = [10, 20, 30, 40];
let middle = &values[1..3];
let text = "café";
println!("{middle:?}");
println!("prefix={:?}, broken={:?}", text.get(..3), text.get(..4));
}[20, 30]
prefix=Some("caf"), broken=None- 1
The array slice covers indexes 1 and 2.
- 2
The accented é occupies two UTF-8 bytes.
- 3
The ..4 boundary splits that character, so get returns None.
cargo run -p lesson_slices03 Mind the boundary
04 Your next build
Write first_two accepting &[i32] and returning up to two elements without panicking on an empty input.
Reveal one possible solution +
fn first_two(values: &[i32]) -> &[i32] {
&values[..values.len().min(2)]
}
fn main() {
assert_eq!(first_two(&[1, 2, 3]), [1, 2]);
assert_eq!(first_two(&[]), []);
}05 Check your reasoning
What do Rust string slice indexes count?
Understand it.
Then make it yours.
Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.