Macro to create array of Vecs

Here the problem is I can't write like this: [Vec::new(); 5]. This would give me a compiler error. I have to repeat Vec::new() five times to initialize the array. So, Is there any macro which does this?

https://crates.io/crates/arr_macro

2 Likes

Thanks

You don't need a crate. You can bypass the Copy requirement with a constant.

const INIT: Vec<u32> = Vec::new();
let vecs = [INIT; 5];
4 Likes

Looks good, but this arr![Vec::new(); 32] is more convenient than this.

const INIT: Vec<u32> = Vec::new();
let vecs = [INIT; 5];

If this works, why can't the compiler just figure it out without having to manually specify the const?

2 Likes

I'm pretty sure the answer is that it hasn't been implemented yet.

1 Like

Conservatism to make implementation feasible. From the RFC (and the PR has more discussion):

Another alternative is to allow a more expansive set of values is_const(expr) rather than is_rvalue_promotable(expr) . A consequence of this is that checking constness would be done earlier on the HIR. Instead, checking if expr is rvalue promotable can be done on the MIR and does not require significant changes to the compiler. If we decide to expand to is_const(expr) in the future, we may still do so as the changes proposed in this RFC are compatible with such future changes.

1 Like

The constant working was an accident, see

IIRC part of this is whether [foo(); 4] calls foo() once (and Copys) or multiple times. Right now I think you can't tell, but as const fn potentially expands to more things then maybe it could matter.

But in the future [const { Vec::new() }, 4] will work (RFC #2920), as will <[_, 4]>::generate(Vec::new) (PR #75644).

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.