Vec indexing, Vec::get, Vec::push, Vec::pop
fn get(&self, index: usize) -> Option<&T>
fn push(&mut self, value: T)
fn pop(&mut self) -> Option<T>
// v[index] via Index, panics when out of boundsRead an element by position. Indexing panics on an out-of-range index; get returns None. push and pop grow and shrink the vector in place.
| Parameter | Description |
|---|---|
index | A zero-based position. It is not a byte offset, even when T is u8. |
value | The element to append. push takes ownership of value. |
Returns: get returns Option<&T> borrowed from the vector. pop returns Option<T> and transfers ownership of the last element. Indexing returns &T, or panics.
Errors and panics
panic— v[index] panics when index >= v.len(). get and pop do not panic for an empty or short vector; they return None.
- Holding a reference from get or from v[i] borrows the vector. You cannot push while that reference is still in use.
- The panic hook in this example is cleared so the failed index can be reported as a boolean without writing a backtrace to stderr.
fn main() {
let mut values = vec![10, 20, 30];
println!("index1={}", values[1]);
println!("get1={:?} get9={:?}", values.get(1), values.get(9));
std::panic::set_hook(Box::new(|_| {}));
let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let _ = values[9];
}))
.is_err();
println!("index9 panicked={panicked}");
values.push(40);
println!("pop={:?} now={:?}", values.pop(), values);
}Expected output
index1=20
get1=Some(20) get9=None
index9 panicked=true
pop=Some(40) now=[10, 20, 30]Related: Vec::get