Vectors
| vec! macro | |
| Push and pop | |
| Indexing | |
| Iterate by reference |
vec! macro
A vector is a growable list that owns its items in order. The vec macro builds one from known values, while Vec new starts empty for later growth:
let v = vec![1, 2, 3];
let mut empty: Vec<i32> = Vec::new();
Push and pop
Use push to add to the end and pop to take from the end. Pop returns Option because the vector may be empty:
let mut v = vec![1, 2];
v.push(3);
let last = v.pop();
Indexing
Brackets read or write one position by index. The get method returns None on a bad index instead of stopping the program:
let v = vec![10, 20, 30];
let first = v[0];
let maybe = v.get(5);
Iterate by reference
Borrow the vector in a for loop to read items without moving ownership. Add mut to the borrow only when items must change:
let v = vec![1, 2, 3];
for x in &v {
println!("{}", x);
}
Next: Slices
Article author: Arthur Isaev