I don't see why printing to stdout in zig is so convoluted. I get that the language is in prerelease, but the fact that there's not as easy way to do it, and they've changed how you do it TWICE makes it really hard to figure out because none of the docs are up to date.

Can you guess which one of these is the current method?

1)

const std = @import("std"); pub fn main() !void { const stdout = std.io.getStdOut().writer(); try stdout.print("Hello, {s}!\n", .{"world"}); }

2)

const std = @import("std"); pub fn main(init: std.process.Init) !void { try std.Io.File.stdout().writeStreamingAll(init.io, "Hello, World!\n"); }

3)

const std = @import("std"); pub fn main() !void { try std.fs.File.stdout().writeAll("Hello, World!\n"); }

Spoiler alert, it's option 2. That's not even the recommended option, because it's unbuffered. You want buffered output? You gotta tack on four extra lines of boilerplate:

const std = @import("std"); pub fn main(init: std.process.Init) !void { var stdout_buffer: [1024]u8 = undefined; var stdout_file_writer: std.Io.File.Writer = .init(.stdout(), init.io, &stdout_buffer); const stdout_writer = &stdout_file_writer.interface; try stdout_writer.print("hello {s}\n", .{"world"}); try stdout_writer.flush(); }

My earlier complaint about the docs is a bit unfair, because the official ones are up-to-date, they're just intentionally sparse to reduce the effort required when making breaking changes. Granted, pre-release is the best time to be doing this, but signposting is very poor. For example, formatting options are documented in exactly one fairly out-of-the-way place despite being shared by several standard library functions.

Follow

@VD15 Isn't this the type of shit you wrap up in your own function of some kind to take care of this slop?

· · Web · 1 · 0 · 0

@xyfdi Yeah, but that's additional friction that just slows down development. In every other language, it's a one-liner. Even C++ in all it's verbosity allows you to pipe something into cout in a quarter of the characters

Sign in to participate in the conversation
Game Liberty Mastodon

Mainly gaming/nerd instance for people who value free speech. Everyone is welcome.