Introduction to Vectors
Introduction to Vectors
- What are Vectors?
Vectors are resizable arrays meaning(they can grow or shrink in size).
Create Vectors
There are two ways to create a vector:
Syntax
- To create a vector write the vector macro
(vec!)
followed by the elements of the vector enclosed in square brackets
- To create a vector write the vector macro
It is optional to define the type and size of the vector enclosed within angular brackets.
Use the vector macro(vec!)
before defining the elements of the vector.
output
Note: Like arrays can be displayed on the screen using the println!() macro.
Access an Element of a Vector
- Any value of the vector can be accessed by writing the vector name followed by the index number enclosed within square brackets
[ ]
.
output
Note: If you try to access an index that does not exist, the compiler will give out of bound access error, ❌.
This is illustrated in the code below:
output
To cater to out of bound exceptions, you can use a None keyword.
output
Print the Vector
output
Methods of Vectors
The methods of vectors are summarized in the chart below:
# | method | explaination |
---|---|---|
1 | Vec::new() | creates a new vector |
2 | .push() | push a value |
3 | .pop() | pop a value |
4 | .contains() | returns true if the vector contains a particular value |
5 | remove(i) | remove value at given index |
6 | .len() | return len of the vector |
The following code demonstrates each of the above methods:
output
Note: When using the .contains function, consider borrowing the value.
Quiz
Test your understanding of basics of vectors in Rust.
Resizing a Vector
- Add Elements to the Vector
- Define a mutable vector variable.
- To add elements to the vector, use the push method.
The following illustration shows how the size of the vector grows by adding an element:
output
Remove Elements from the Vector
- Define a mutable vector variable.
- Elements can be removed from the tail or at specific index of the vector.
- To remove elements from the tail of the vector, use the pop method.
- To remove elements at a specific position of the vector, specify the index number within the
remove()
method.
output:-
Note that the remove()
function requires the index of the vector element to be removed. However, if it is desired to pass the element to be removed,
then we need to know the index of the particular element of the vector and then remove it. Let’s explore that in the next lesson using the .iter()
method.
Last updated a year ago.