Linux Format

THE VECTOR DATA TYPE

-

The Vector data type is very popular in Rust, so it deserves some extra attention. First of all, a Vector is like an array. As is the case with arrays, index values start from 0. The main advantage of vectors over arrays is that vectors can be resized, provided that they’re declared as mutable. You can put or remove vector elements using pop() and push(), respective­ly. Additional­ly, apart from the size, which is the number of elements stored, a vector has a capacity, which is the amount of memory reserved for the vector. Finally, a vector represents a pointer to the data.

You can select the part of a Vector that you want to access using an index range, as occurs in read.rs. So, for a vector named a_vector, you can select its first two elements by writing &a_vector[0..2] . You can iterate over the elements of a vector in various ways. One such way is by using a for loop using the index of the element you want to access. Another approach is to use an iterator, which for a_vector is called as a_vector.iter() , to obtain all vector elements one by one. Remember that if you use an index value greater than or equal to the length of the vector, your code is going to crash.

The same is going to happen if you use pop() on an empty vector. The solution to both issues is to use a match block to check whether you’re trying a valid operation or not.

All these and many more are illustrate­d in vector.rs. Feel free to look at the code of vector.rs and experiment with it. Running vector.rs produces the following type of output (some output is omitted): a_vector is: [2, -2, 12]

The first element of a_vector is 2

... an_element is None

Pop(): it is not defined!

Newspapers in English

Newspapers from Australia