Indexing and Iterating
Access and loop over elements.
Reading by Index
Each element in a vector has a position number called an index. Indexes start at 0, so the first element is index 0.
Read an element with square brackets, like v[0] for the first value.
fn main() {
let v = vec![100, 200, 300];
println!("first = {}", v[0]);
println!("third = {}", v[2]);
}Out of Bounds Panics
Indexing past the end of a vector causes a panic and stops the program. For a vector of length 3, the only valid indexes are 0, 1, and 2.
Asking for v[5] here would crash, so always make sure the index is in range.
All lessons in this course
- Creating and Filling Vectors
- Indexing and Iterating
- Growing and Shrinking
- Vectors of Structs