Borrow vector elements safely
Quick answer
Borrow vector elements instead of moving owned values out by indexing. Use get when an index may be invalid and get_mut when you need to change one item.
Bounds and borrowing
v.get(i) returns Option<&T>, whereas v[i] panics if the index is outside the vector. A mutable borrow must not overlap a live shared borrow. Growing a vector may relocate its elements, so Rust prevents mutation while a reference to an element is still needed.
fn main() { let names = vec![String::from("Ada")]; if let Some(name) = names.get(0) { println!("{name}"); } println!("missing: {}", names.get(2).is_none());}Expected stdout (not executed):
Adamissing: trueNo ownership is transferred.
fn main() { let mut v = vec![10]; let first = &v[0]; v.push(20); println!("{first}");}Expected: compilation fails; exact diagnostic not verified.
Move the print before push, or copy the number into an owned value.
Common mistake
Do not assume reserved capacity makes overlapping borrows legal.
Try it yourself
Use get_mut to increase the second element of a vector only if it exists.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Borrow vector elements safely — practice quiz
Choose one answer per question, then review the explanation.
For `let v = vec![2, 6];`, what does `v.get(1)` return?
What does indexing a vector at its length do?
Why may push be rejected while an element reference is still used later?