Vectors

Vectors are the primary linear collection type in Rust. They are mutable, growable lists of values, represented as a struct in memory.

Vectors can be initialised in two main ways:


    

As can be seen in the above example, there is a shorthand macro, vec!, for quickly initialising a vector and immediately filling it with values (although empty vectors can still be made by leaving the macro's square brackets empty). The shorthand syntax that can be used with arrays can also be used with this macro:


    

As with arrays, individual elements of vectors can be accessed with indexing...:


    

...and iterated over with loops:


    

Exercise:
Try initialising a vector of chars, before iterating over it with .iter() (remember the page on arrays and slices?):


    

Vectors also have a multitude of useful built-in methods (such as push(), demonstrated above) that allow for easily accessible operations on them and their elements. For example: