Safe Slice Access With Get And GetMut
Read and mutate slices without panics: get returns Option<&T>, get_mut returns Option<&mut T>, and plain indexing stays for provably in-bounds access.
Code
fn main() {
let mut scores = vec![70, 85, 92];
// get returns Option<&T>: out of bounds yields None instead of a panic
println!("get(1) = {:?}", scores.get(1));
println!("get(9) = {:?}", scores.get(9));
// get_mut returns Option<&mut T>: only a Some grants write access
if let Some(top) = scores.get_mut(2) {
*top += 3;
}
println!("after get_mut: {:?}", scores);
// When the index is provably in bounds, plain indexing is terser; out of bounds it panics
let known = &scores[0];
println!("index [0] = {known}");
// get works on slices and str too (indexed by byte)
let name = "golang";
println!("name.get(1..3) = {:?}", name.get(1..3));
}How it works
Safe Slice Access With Get And GetMut keeps everything in the function main.
What to watch for
- No dependencies section needed; the standard library is the whole story.
Putting it to use
The primary signature is fn main()
Output lines are prefixed (get(1) =, get(9) =, after get_mut:), making each step’s effect easy to spot.
Core lines
if let Some(top) = scores.get_mut(2) {
*top += 3;
}
Interactive Tools for This Topic
FAQ
- What does Safe Slice Access With Get And GetMut print when run?
- Running the file directly is enough — expect labeled output lines such as `get(1) =`, `get(9) =`, `after get_mut:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.