Vectors
8 min · Rust
Rust's resizable lists — Vec holds many values in order.
Enemy 1 of 5
So far every variable has held a single value. A Vec<T> (short for "vector") holds many values of the same type T, one after another, in order — it's Rust's equivalent of Python's list or JavaScript's array. The <T> is a generic placeholder: a Vec<i32> holds integers, a Vec<&str> holds string slices, and so on. Rust figures out T automatically from the values you give it, so you rarely have to write it yourself.
The vec! macro (notice the exclamation mark again — this is another macro, just like println!) is the easiest way to build a vector with some starting values: vec!["apple", "banana", "cherry"]. Once you have one, you reach into it with square brackets and a position, counting from 0: fruits[0] is the first item, fruits[1] the second, and so on. Asking for an index that doesn't exist — like fruits[10] on a 3-item vector — will crash the program at runtime with an out-of-bounds panic rather than silently returning something like undefined or None, which is a deliberate Rust safety choice.
Loading editor...