Vec is a generic type for allocating a growable array in the heap memory.
We present here the basics of the Vec type and some of its methods. See
Table 1 for a more complete list of its methods.
Table 1:Some methods of Vec
Method | Description |
|---|---|
| Appends another |
| Removes all elements. |
| Removes consecutive repeated elements. |
| Inserts the value |
| Returns |
| Returns the number of elements. |
| Creates a new vector. |
| Removes the last element and returns it. |
| Appends the value |
| Removes an element at position |
| Resizes the vector to size |
| Shortens the vector to size |
18.1.1Empty vector¶
Example of an empty vector of signed bytes:
let v: Vec<i8> = Vec::new();
v[]18.1.2Adding elements¶
Using the push() we can add elements one by one:
let mut v: Vec<i8> = Vec::new();
v.push(10);
v[10]18.1.3vec! macro¶
The vec! macro allows to
initialize a Vec instance with values as it is done with standard
arrays.
The first form of vec! takes a list of values:
let v = vec![1, 2, 3];
vCouldn't automatically determine type of variable `v`.
Please give it an explicit type.The second form of vec! takes a value and a number of repetitions:
let v = vec![5; 10];
v18.1.4Accessing elements by index¶
We can access individual elements using the indexing operator ([]):
let v = vec![1, 2, 3];
v[1]With this operator, if the index is out of bounds, an unrecoverable error is raised:
let v = vec![1, 2, 3];
v[5]18.1.5Modifying elements by index¶
We can modify the values of a mutable vector using the indexing operator:
let mut v = vec![1, 2, 3];
v[2] = 8;
v18.1.6Iterating over elements¶
Using the for statement (see for), we can iterate over the
elements of a vector:
let v = vec![1, 2, 3];
for e in v { // v is moved (see the warning below)
print!("{e}, ");
}The same can be done by obtaining an iterator explicitly using the
into_iter() method. The Iterator object can then be iterated over
thanks to the next() method, which returns an Option<T>:
let v = vec![1, 2, 3];
let mut i = v.into_iter(); // v is moved (see the warning below)
while let Some(e) = i.next() {
print!("{e}, ");
}