Welcome fellow Rustaceans to this article. For this one, we will discuss how to work with vectors in the Rust programming language.
Rust Create New Vector
There are two primary methods to create a vector in Rust.
The first is to create a new instance of the vector struct using the new() method. The syntax is as shown below:
Note that we specify the vector type inside a pair of angle brackets.
An example of a vector is shown below:
let vect: Vec<i32> = Vec::new();
}
The above examples create a new empty vector of 32-bit signed integers.
The second method to create a vector is to use the vec! Macro. This is a built-in macro that allows you to declare and initialize a new vector.
The syntax is as shown below:
In this format, we do not need to annotate the vector type. The compiler will infer the type based on the values stored in the vector.
An example is as shown:
let vec = vec![1,2,3,4,5];
}
Accessing Vector Values
We can access the values of a vector using two methods.
The first is to use the index notation. To use the index notation, we start with the vector name and the index of the value we wish to access inside square brackets.
NOTE: Vector indexing starts at index 0. Hence, the first value in the vector is at index 0.
An example is as shown:
let vec = vec![1,2,3,4,5];
println!("{}", vec[0]);
}
The code above should return the element at index 0. In this case, it should return 1.
Although accessing vector elements by the index is suitable for small use-cases, it presents a problem if we access an out-of-bound index.
Take the example vector below:
The last element is at index 4. If we attempt to access an index above 4, the program will panic and exit. An example is as shown:
let vec = vec![1,2,3,4,5];
println!("{}", vec[5]);
}
The code above will return an error as:
We can overcome this by using the get() method. This method takes the index we want to access and returns the associated value.
let vec = vec![1,2,3,4,5];
println!("{:?}", vec.get(0));
}
In the above example, the function returns a value using the Option enum. Check the enum documentation to learn more.
Unlike the square bracket notation, this function returns None if the index is not found instead of panicking.
let vec = vec![1,2,3,4,5];
println!("{:?}", vec.get(5));
}
Since the index of the array does not exist, the function returns none as shown below:
Iterating over a Vector
We can easily iterate over the index and elements of a vector using the iter method. An example is as shown below:
let vec = vec![1,2,3,4,5];
// println!("{:?}", vec.get(5));
for i in vec.iter() {
println!("{}", i);
}
}
We can also enumerate the vector using the enumerate method. This returns the index and value as below:
let vec = vec![1,2,3,4,5];
for (index, value) in vec.iter().enumerate() {
println!("Index: {}, value: {}", index, value);
}
}
The code above should return the output as:
Index: 1, value: 2
Index: 2, value: 3
Index: 3, value: 4
Index: 4, value: 5
Add & Remove Vector Items
Rust allows us to add or remove items from a vector using the push and pop methods. This adds and removes a specified item to and from the vector stack, respectively.
The example below shows how to add an item to a vector.
let mut vec = vec![1,2,3,4,5];
vec.push(6);
println!("{:?}", vec);
}
This prints a vector as:
To remove an item from the vector stack, use the pop method as shown:
let mut vec = vec![1,2,3,4,5];
vec.pop();
println!("{:?}", vec);
}
This should remove the specified value from the vector and return:
NOTE: The vector must be mutable for push or pop operations.
Find Value in Vector
You can find if a vector contains a value using the contains() method. An example is as shown:
let mut vec = vec![1,2,3,4,5];
if vec.contains(&5) {
println!("found!")
} else {
println!("not found!");
}
}
The contains() method checks if a value is in the vector and returns a Boolean value.
In Closing
This article describes vectors, how to create and perform various operations on them. You can check the Rust documentation to learn more.
Thanks for reading!