Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rust initialize vector using macro and fill it with value from exsting array

I’m learning rust using the rustlings, however I am not able to understand this issue: How can I initialize new Vector using the vec! macro and automatically fill it up with values from exiting 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?

What do I want?: I want to initialize new vector using the vec! macro and in the same line fill it with values from the a array values.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 annoation 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];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading