Rust Slices
Borrow part of a collection with a checked boundary.
How it works
A slice references a contiguous range of elements without owning a new collection. Its length is part of the reference metadata, and indexing or range construction must obey boundaries. get returns Option for a possibly invalid range, which is useful at an input boundary. Slices make APIs flexible because callers can supply arrays or vectors without transferring ownership.
Run the code
Reviewed with Rust 1.97.0, edition 2024, using the standard library only. Save the complete download as lesson-name.rs in a separate learning folder, compile with rustc --edition=2024 lesson-name.rs and run the resulting program (lesson-name.exe on Windows). Use the actual lesson filename. The final project includes complete Cargo package files; run cargo test --offline and cargo run --offline from that separate package folder. There is no Rust browser runner; PHP, Apache and MySQL are not needed.
This complete example was executed in the stated local review environment.
Example
fn main() {
let counts = [3, 5, 8, 2];
let selected = counts.get(1..3).expect("known fixture range");
assert_eq!(selected, &[5, 8]);
assert!(counts.get(9).is_none());
println!("Borrowed middle counts: 5 and 8");
}
Expected result
Borrowed middle counts: 5 and 8
The range excludes its upper endpoint, selecting positions one and two. The second check demonstrates a safe refusal rather than an indexing panic. For data supplied by a request or file, propagate the None case as an appropriate validation result instead of using expect.
Primary technical reference: Rust documentation.