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?
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];
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
?
I'm pretty sure the answer is that it hasn't been implemented yet.
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 thanis_rvalue_promotable(expr)
. A consequence of this is that checking constness would be done earlier on the HIR. Instead, checking ifexpr
is rvalue promotable can be done on the MIR and does not require significant changes to the compiler. If we decide to expand tois_const(expr)
in the future, we may still do so as the changes proposed in this RFC are compatible with such future changes.
The constant working was an accident, see
IIRC part of this is whether [foo(); 4]
calls foo()
once (and Copy
s) 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).
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.