3 ms·
Question for Zig experts: for (elems) |x| { std.debug.print("{} ", .{x}); } Why is the .{x} necessary here? What happens if I just write "x"?
by hota_mazi 4y ago
Question for Zig experts:
for (elems) |x| {
std.debug.print("{} ", .{x});
}
Why is the .{x} necessary here? What happens if I just write "x"?
- anonymoushn 4y ago`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.
- quic5 4y agoThe 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/f6c934677315665c140151b8dd28a56f948205e2/lib/std/debug.zig#L89 https://github.com/ziglang/zig/blob/f6c934677315665c140151b8...
- AnIdiotOnTheNet 4y agoZig 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.
- Laremere 4y agoZig 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 https://github.com/ziglang/zig/blob/master/lib/std/fmt.zig