Vectors
Last updated
Last updated
A vector is a similar collection type provided by the standard library that is allowed to grow or shrink in size.
Vectors are implemented using generics.
More often, you’ll create a Vec<T>
with initial values and Rust will infer the type of value you want to store, so you rarely need to do type annotation.
References:
Rust conveniently provides the vec!
macro, which will create a new vector that holds the values you give it.
You can specify the vector types the type within angle brackets like Vec<i32>
.
More often, you’ll create a vector with initial values and Rust will infer the type of value you want to store, so you rarely need to do this type annotation.
In this exercise we just need to init new vector using vec!
macro.
In this exercise we have 2 task:
First is to iterate through a collection manually using for
and multiply each element with 2
.
Multiple element
by 2
.
Then push it into output
variable.
Second is to iterate through a collection using iterators and multiply each element with 2
.
Calling iter()
to a collection will return Iter
type.
collect()
can take anything iterable, and turn it into a relevant collection.
You can read more about it in .
Then calling map()
to produces a new iterator which calls given closure on each element of the original iterator. Ref: .
You can read more about iterators in here: and the trait here" .