Const constructor of Vec


#1

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.


#2

You should be able to use vec![].


#3

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?


#4

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.


#5

Mutex::new() is a const fn in newer nightlies. https://github.com/rust-lang/rust/blob/master/src/libstd/sys_common/mutex.rs#L27


#6

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…


#7

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.


#8

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


#9

So it looks like at the moment we are blocked by https://github.com/rust-lang/rust/issues/49146


#10

However, it looks like we can work around it for now: https://github.com/rust-lang/rust/pull/50233


#11

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