Hello World

Hello World

hello.zig

const std = @import("std");

pub fn main() !void {
    // If this program is run without stdout attached, exit with an error.
    const stdout_file = try std.io.getStdOut();
    // If this program encounters pipe failure when printing to stdout, exit
    // with an error.
    try stdout_file.write("Hello, world!\n");
}
``` ```
$ zig build-exe hello.zig
$ ./hello
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

const warn = @import("std").debug.warn;

pub fn main() void {
    warn("Hello, world!\n");
}
``` ```
$ zig build-exe hello.zig
$ ./hello
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:

  • Values
  • @import
  • Errors
  • Root Source File