Vector macro on array variable?

Viewed 545

Just curious, is there a way to define a Vector with the vec! macro on an array variable?

The bellow code compiles fine:

let a = [1,2,3,4]
let v = vec![1,2,3,4]

But I get a mismatched types error when compiling this:

let a = [1,2,3,4]
let v = vec!a

This seems like it should intuitively work but I'm coming from Python so I often expect little shortcuts like that and that sometimes leads me astray. What's the best way to quickly initialize a Vector with the values in an already-existent array?

1 Answers

You can just convert the slice to a Vector with a.to_vec().

Rust macro is defined so that it can be used against specific patterns of expression. A simplified vec!, for instance, can be found here. As you can see from the definition, the expression must match pattern defined as ( $( $x:expr ),* ), i.e. the pattern must be enclosed with a pair of parenthesis to begin with. Expression a doesn't match this pattern.

Related