Hello World

hello.zig

  1. const std = @import("std");
  2. pub fn main() !void {
  3. // If this program is run without stdout attached, exit with an error.
  4. const stdout_file = try std.io.getStdOut();
  5. // If this program encounters pipe failure when printing to stdout, exit
  6. // with an error.
  7. try stdout_file.write("Hello, world!\n");
  8. }
  1. $ zig build-exe hello.zig
  2. $ ./hello
  3. Hello, world!

Usually you don't want to write to stdout. You want to write to stderr. And you don't care if it fails. It's more like a warning message that you want to emit. For that you can use a simpler API:

hello.zig

  1. const warn = @import("std").debug.warn;
  2. pub fn main() void {
  3. warn("Hello, world!\n");
  4. }
  1. $ zig build-exe hello.zig
  2. $ ./hello
  3. Hello, world!

Note that we also left off the ! from the return type. In Zig, if your main function cannot fail, you must use the void return type.

See also: