Why can't I have unsized statics (or consts)?

Statics are stored in the .data section of the binary, and we can take their address. Why can I have e.g. a static &[u16]

static x: &[u16] = &[1, 2, 3];

but not a static [u16]

static y: [u16] = &[1, 2, 3];

Statics must be initialised with a constant value, so there is no problem that the compiler does not know the actual size the of the object that will be put into the static (even if it the type is not Sized in general), and thus how much space to reserve and how to initialise it. What is the reason that ?Sized statics aren't allowed?

You couldn't create a & to it without knowing the size. (References and pointers to unsized types are wide pointers which include some sort of metadata from which you can get the size. In the case of slices, that's the number of elements.)

Sure, but at compile-time, because a static must be initialised with a constant value, that should be known, right? Are there cases I don't see where this is not known, or is it simply a limitation of the compiler?

I don't know what you are going to do with an "unsized static" except create a reference to it anyway, so I'm not sure what advantage it offers over your first example. (I guess with unsized_locals feature you could copy it to the stack or something, but also I don't know how the size would be communicated)

An array sounds closer to what you want, but unfortunately you do need to tell it the length:

static y: [u16; 3] = [1, 2, 3];

It would be nice if you could have the compiler infer the length in the type definition.

4 Likes

You mean, just fill in the length for you implicitly everywhere? That would be inconsistent with everything else in the language, and surprising for a strictly typed language. It'd be a [i16; n] as @rschoon said, not a [i16].

Agreed.

1 Like

Because ?Sized is just the wrong name (as many things in Rust).

Rust does not support unsized types (and I'm not even sure how it should). What it does support are dynamically sized types.

Static is, most definitely, not a dynamically sized type thus asking why [u16] can not be static is pretty much pointless.

But yeah, it would have been nice if size of static array would have been defined automagically. I guess no one wanted that badly enough.

1 Like

It's the same decision that requires that you put the type of the array there.

It would be easy for the compiler to support static FOO = [0_u8, 1, 2];, but the language has intentionally decided not to. (See also requiring that you write parameter types and return types on functions.)

For further reading, you might be interested in https://github.com/rust-lang/rfcs/pull/2545#issuecomment-661305546

1 Like

What does that really buy you over specifying the length? It seems to me it just makes it much easier to accidentally omit or duplicate a value and end up with the wrong size. Specifying the size is a nice sanity check.