Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

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

append(other)

Appends another Vec object to this one.

clear()

Removes all elements.

dedup()

Removes consecutive repeated elements.

insert(i, v)

Inserts the value v at a position i.

is_empty()

Returns true if the vector contains no elements.

len()

Returns the number of elements.

new()

Creates a new vector.

pop()

Removes the last element and returns it.

push(v)

Appends the value v.

remove(i)

Removes an element at position i.

resize(sz, v)

Resizes the vector to size sz, appending copies of v if required.

truncate(sz)

Shortens the vector to size sz.

18.1.1Empty vector

Example of an empty vector of signed bytes:

[]

18.1.2Adding elements

Using the push() we can add elements one by one:

[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:

Couldn'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:

18.1.4Accessing elements by index

We can access individual elements using the indexing operator ([]):

With this operator, if the index is out of bounds, an unrecoverable error is raised:

18.1.5Modifying elements by index

We can modify the values of a mutable vector using the indexing operator:

18.1.6Iterating over elements

Using the for statement (see for), we can iterate over the elements of a vector:

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>:

see solution