Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vector

rust

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?

like image 695
TDiblik Avatar asked Mar 23 '26 08:03

TDiblik


1 Answers

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];
like image 154
Chayim Friedman Avatar answered Mar 24 '26 23:03

Chayim Friedman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!