Const constructor of Vec


I was wondering why there isn’t a const fn to create a new empty Vec. It seems like this ought to be possible: it just doesn’t allocate any memory.

Having something like that would allow you to have static initializers with Vec in them without using lazy_static.


You should be able to use vec![].


But why do you want a static Vec without lazy_static anyway? If your static is immutable, why don’t you use a primitive, sized array instead? If your static is mutable, and you want to grow the vector, how do you want to ensure thread/concurrency/memory safety? Do you always want to make manual unsafe locking code around your static?


I’ve definitely seen Vec::new() get thrown around a few times as an example of a function that could be const fn, and now that we allow Drop types in consts I’m not aware of any reason not to make it a const fn. I think we just haven’t gotten around to it yet.


Mutex::new() is a const fn in newer nightlies.


You can also use something like spin::Mutex, which has a const constructor and works on no_std.

I think it’s always possible to use lazy_static. However, TBH, it really annoys me. I’ve tried many times to get used to it, but I really shouldn’t need the extra layers around my static just to initialize it at the very beginning of the program anyway…


As a general rule: Everything that can be const fn should be const fn, unless we have reason to believe that future developments might change that.


Oh yeah, right. That’s a fair point, so we do have const-constructible locking types.


So it looks like at the moment we are blocked by


However, it looks like we can work around it for now:


Yay! My PR merged, so this is actually done now…