Rust Vectors

Rust has a standard collection library that provides a number of collections, which, like an array, store multiple values of the same type. A vector is one of the collection types available in Rust. It is basically an array that can be resized.

The example below creates a vector called 'names', adds four names using the 'push' method, then displays them in the console/terminal one at a time using a ‘for’ loop.

let mut names = Vec::new();

names.push("Bob");
names.push("George");
names.push("Fred");
names.push("Alan");

for name in names.iter()
{
    println!("{}", name);
}

The output from this will be as follows.

Bob
George
Fred
Alan

The declaration and initialisation of the vector can be done more efficiently by combining the two, whilst still allowing the loop to process the vector in the same way.

let mut names = vec![
    "Bob",
    "George",
    "Fred",
    "Alan"
];

As with arrays, each value within a vector has an index value, which starts at zero for the first item. This can be used to retrieve a single value, such as the first, as shown below.

println!("{}", names[0]);

Similarly, the index can be used to update an individual value. Here, the second value is changed to 'Janice'.

names[1] = "Janice";

Using the 'remove' method, together with an index value, a specific value can be removed from a vector.

names.remove(1);

If it is necessary to find out how many values are in a vector, this can be achieved using the 'len' method.

println!("The size of the vector is: {}", names.len());

To check if a specified value exists within a vector, the 'contains' method can be utilised.

if names.contains(&"Bob")
{
    println!("The value 'Bob' is in the vector.");
}
else
{
    println!("The value 'Bob' is not in the vector.");
}