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 Likes

#2

You should be able to use vec![].

0 Likes

#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?

1 Like

#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.

1 Like

#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

0 Likes

#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…

0 Likes

#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.

3 Likes

#8

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

0 Likes

#9

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

1 Like

#10

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

1 Like

#11

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

1 Like

closed #12

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.

0 Likes