Re:Zig's Curious Multi-Sequence for Loops
by hota_mazi on Monday February 27, 2023 @10:22AM
(#34957415)
Question for Zig experts:
Why is the .{x} necessary here? What happens if I just write "x"?
[ Parent
| on HN ]
Re:Zig's Curious Multi-Sequence for Loops
by Laremere on Monday February 27, 2023 @10:40AM
(#34957670)
Zig doesn't have variable length args. The .{} syntax is for an anonymous struct with no field names (which are named tuples in Zig.) Print takes the struct's type info at compile time to check the validity of the statement, and also produce optimal code. This is implemented entirely within Zig's standard functionality that's available to all users.
So, if you just type X, you're getting an error about it not being a struct. That's unless X is a struct with one field, where it'll just print that field. I find Zig meta-programming to actually be fairly readable, here's the function that does the formatting: https://github.com/ziglang/zig/blob/master/lib/std/fmt.zig
Re:Zig's Curious Multi-Sequence for Loops
by anonymoushn on Monday February 27, 2023 @10:25AM
(#34957443)
`std.debug.print` and similar fmt-like functions take 2 arguments. The first argument is a format string, and the second argument is a tuple. I think a tuple is an anonymous struct whose members are named 0, 1, 2, etc., but I'm not completely sure on this. If you just write "x", it won't work, since you needed to pass a tuple containing 1 thing, and x probably isn't a tuple containing 1 thing.
The print function is implemented in the std library[1] not the compiler and Zig does not have varargs
[1] https://github.com/ziglang/zig/blob/f6c934677315665c140151b8...
Re:Zig's Curious Multi-Sequence for Loops
by AnIdiotOnTheNet on Monday February 27, 2023 @10:28AM
(#34957493)
Zig doesn't have varargs anymore. Instead, it has anonymous structs/arrays/tuples. The second argument to `print` here is expected to be a list of the values referenced by the `{}` placeholders in the string in the first argument.
`.{a, b, c}` is the syntax for an anonymous struct/array/tuple, and a single element still needs to be wrapped in it.