#What 'kind of something' is the [_]u8 part to the right of the equal sign if not a type, for arrays?

1 messages · Page 1 of 1 (latest)

verbal sedge
#

Seeing that integers and booleans have their type declaration to the left of the equal sign after a double colon:

var int: u8 = 4;
var toggle: bool = undefined;

I tried, just for sake of a better understanding, to replicate this for string literals and arrays:

const where_is_my_base: *const [7:0]u8 = "ask_zig";
const array: [3]u8 = [_]u8{ 1, 2, 3 }

But leaving off the []u8 part fails. Altough remember seeing it used somewhere, maybe by mistake?
Anyway, someone told me this [
]u8 is not the type, but what is it then? And why is it essential to add it to the right of the equal sign this time... while other types do this to the left? I'm realising the zig devs made very conscious decisions all around, so i'd like to know the reasoning behind this. Who enlightens me? 😉

subtle hound
#

It's kind of a type but also not

#

I'd call it a "constructor" probably

#

[_]u8{ ... } basically says "create an array of u8, the length of which is determined by the number of items in the literal"

#

why is it essential to add it to the right of the equal sign this time
It isn't

#

const array: [3]u8 = .{ 1, 2, 3 } is valid

#

So is const array = [_]u8{ 1, 2, 3 } which is more useful if you want to infer the length

#

const array = [3]u8{ 1, 2, 3 } is also valid, though putting the type to the left of the equals is generally preferred

verbal sedge
#

Aaah the . ofcourse

subtle hound
#

tl;dr use const array: [3]u8 = .{ 1, 2, 3 } if you want to check the length of the literal, const array = [_]u8{ 1, 2, 3 } if you want to infer it :)

verbal sedge
#

Yes, awesome

#

Btw I did notice the compiler can infer the length anyway. So why isn't it possible to do it 'to the left' with an underscore?

subtle hound
#

Because the thing on the left has to be a type

#

And [_]u8 isn't a type

verbal sedge
#

Alright I'm growing to like this [_]u8 guy, he's very misterious and undefinable 😉

subtle hound
#

heheh

#

Lemme see what the grammar calls it :)

#

The grammar doesn't really distinguish between [_]u8{ ... } and any other array initializer

#

It's probably better not to separate the [_]u8 from the { ... }

#

It doesn't really make much sense without the braces

#

So the whole thing, [_]T{ ... }, is a type of array initializer

#

You could call it an "inferred length array initializer"

#

Or an "inferred length array literal"