0

While experimenting with the zig syntax, I noticed the type expression of string literals is omitted in all examples. Which is totally fine, I'm not saying it shouldn't be.

const zig_string = "I am a string"; //it looks nice enough for sure and compiles fine ofcourse

However, because this type omission is a bit inconsistent* with other type declarations in zig, it can lead to beginners (like me) misinterpreting the actual type of string literals (which is fact quite rightfully complicated and 'different'). Anyway, after reading about the type of string literals being 'pointers to (utf-8 encoded) immutable (const), sentinel terminated arrays of u8 bytes' (yes?), with next to the hard coded length field, a terminator field like so: [<length>:0]. To check my own understanding, I thought it reasonable to try adding this type expression to the declaration, similar to how other arrays are conveniently declared, so with an underscore to infer the length, because who likes counting characters?

const string: *const [_:0]u8 = "jolly good"; //doesn't compile: unable to infer array size

But it didn't compile :(. After dutifully counting characters and now specifying the length of my string however, it proudly compiled :)!

const string: *const [10:0]u8 = "jolly good"; //happily compiles

Which led me to my question:

  • Why is this length specification needed for string literals and not for other literals/arrays? - (And should this be so?)
  • Please correct my type description of string literals if I missed an important nuance.

I'd like to know to further deepen my understanding of the way strings are handled in zig.

*although there are more cases where the zig compiler can infer the type without it

Gaai
  • 98
  • 1
  • 8

1 Answers1

0

Types never have _ in them.
"jolly good" is a string literal. *const [10:0]u8 is the type.

For "other literals/arrays":

const a = [_]u8{ 1, 2, 3 };

[_]u8{ 1, 2, 3 } is an array literal. The type is [3]u8 and it cannot be specified as [_]u8.

Look into slices. They offer a very convenient way to use strings and arrays.

sigod
  • 3,514
  • 2
  • 21
  • 44
  • Thanks for taking tge time to answer me. I'm confused now. Why 11, null terminator isn't part of the length right? And why is [_]u8 not the type specification of the array? Because it's after the equal sign? Slices are indeed great. – Gaai Nov 13 '22 at 09:06
  • I suppose const a: [3]u8 = { 1, 2, 3 }; would be the correct type specification of your array. With the colon and to the left of equal sign. Also i am pretty sure you just mistyped the 11 for my string size? Anyway, would there be a similar way to declare a string literal with the infer [_] to the right of the equal sign? – Gaai Nov 13 '22 at 09:59
  • That'd be: const a: [3]u8 = [3]u8 { 1, 2, 3 }; – Gaai Nov 13 '22 at 11:26
  • @Gaai Yes, 11 was a mistake. Sorry for confusing you. – sigod Nov 13 '22 at 16:30