Reputation: 577
From what I understand, &[T]
type is a 'fat' pointer (memory address and size) and not the slice itself and [T]
is the actual slice that is being referenced. But why didn't they make [T]
a syntax error in the context below?
let y: [i32; 6] = [1, 2, 3, 4, 5, 6];
// let z: [i32] = y[..]; // error: the size for values of type `[i32]` cannot be known at compilation time
let z: &[i32] = &y[..]; // OK
// let v: str = "Hello World"; // the size for values of type `str` cannot be known at compilation time
From the error: [i32] cannot be known at compilation
, is this just an error to make me, the user, understand why this syntax isn't possible or is it because I'm not using this syntax right and it is valid in some context?
Upvotes: 0
Views: 165
Reputation: 26549
Because it is possible to use unsized types like str
, [T]
, and dyn MyTrait
in some contexts.
The most common at the moment is in generics. You can, for example, have a Box<[T]>
or Box<str>
, Arc<[T]>
, or any generic with a ?Sized
bound.
There's also a few in-development features using such unsized types:
struct
with one unsized field, making the struct itself unsized. Pretty useless at the moment though, since you can't actually create such a structure.Upvotes: 5
Reputation: 42207
But why didn't they make [T] a syntax error in the context below?
Because there's nothing about the syntax that has any reason to be invalid?
While DSTs are difficult to work with and don't make sense everywhere, there are contexts in which they are perfectly legal e.g.
struct Foo {
a: usize,
b: [i32]
}
Upvotes: 2