TDiblik
TDiblik

Reputation: 622

Initialize vector using vec! macro and fill it with values from existing array

How can I initialize new Vector using the vec! macro and automatically fill it up with values from an existing array? Here's the code example:

let a = [10, 20, 30, 40]; // a plain array
let v = vec![??];       // TODO: declare your vector here with the macro for vectors

What can I fill in (syntax wise) instead of the ??? characters?

Upvotes: 10

Views: 9253

Answers (3)

Chayim Friedman
Chayim Friedman

Reputation: 71370

Since Vec<T> impls From<[T; N]>, it can be created from an array by using the From::from() method or the Into::into() method:

let v = Vec::from(a);
// Or
let v: Vec<_> = a.into(); // Sometimes you can get rid of the type 
                          // annotation if the compiler can infer it

The vec![] macro is not intended for that; it is intended for creating Vecs from scratch, like array literals. Instead of creating an array and converting it, you could use the vec![] macro:

let v = vec![10, 20, 30, 40];

Upvotes: 14

jwchoi
jwchoi

Reputation: 737

I'm new to rust.

I think the question comes from rustlings / exercises / vecs that help understand basic syntax for rust.

fn array_and_vec() -> ([i32; 4], Vec<i32>) {
    let a = [10, 20, 30, 40]; // a plain array
    let v = // TODO: declare your vector here with the macro for vectors

    (a, v)
}

When I try to solve the problem, I searched whether there is a way to enumerate all element in the existing array and use it to construct vector by using vec! macro. It is easy to use Vec::from. However, it's not macro but a function. Or the exercise does not make sense?

Upvotes: 2

Netwave
Netwave

Reputation: 42756

You can also use the to_vec method:

let a = [10, 20, 30, 40]; // a plain array
let v = a.to_vec(); 

Playground

A per the comments, notice that it clones the elements, so the vector items should implement Clone.

Upvotes: 7

Related Questions