Coder
Coder

Reputation: 1909

What is the idiomatic way to create a Vec of a specific data type using the vec macro?

Something like let v = vec![1, 2, 3]; would default to i32 but I would like to specify the type as u8.

One alternate is to create with:

let v: Vec<u8> = vec![1, 2, 3];

or

let v: Vec<u8> = Vec::new();
v.push(1);
v.push(2);
v.push(3);

Is there a better way to directly use the macro? In both cases, I need to declare a variable.

Sometimes, I need to use the vector in an assert statement. If there was a way to avoid creating the variable, I could have written:

pub fn func1() -> &[u8] {
  // return slice [1, 2, 3] of [u8];
}
assert_eq!(vec![1, 2, 3], func1());

Upvotes: 8

Views: 4008

Answers (2)

Niklas Hallqvist
Niklas Hallqvist

Reputation: 131

Although I am not sure about the idiomacy of the way, I'd propose

vec![1, 2, 3] as Vec<u8>

or just define a macro as suggested:

macro_rules! tvec [
    ($t:ty; $($e:expr),*) => { vec![$($e as $t),*] as Vec<$t> }
];

and use it like tvec![u8; 1, 2, 3] This works for empty vectors as well. Here's a playground example

Upvotes: 5

lkolbly
lkolbly

Reputation: 1240

The type of the vector will be automatically deduced in that situation. This compiles fine:

fn func1() -> Vec<u8> {
    vec![1, 2, 3]
}

fn main() {
    assert_eq!(func1(), vec![1, 2, 3]);
}

if you need to explicitly specify the type, you can do something like vec![1u8, 2, 3]

Upvotes: 11

Related Questions