Zig Get Started
Getting started with Zig means writing a small program file and running it with the Zig tool. Every program in this course uses the same basic shape.
The standard shape prints a line
The first line loads std. The main function then prints one line with out.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
try out.print("Hello from Zig!\n", .{});
}Code inside main runs in order
The lines inside main run from top to bottom. The output shows that order.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
try out.print("Start\n", .{});
try out.print("Finish\n", .{});
}The lines in main run when the program runs
A program does its work inside main. This program prints a single message from there.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
try out.print("Inside main\n", .{});
}Example
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
try out.print("Ready\n", .{});
try out.print("Set\n", .{});
try out.print("Go\n", .{});
}Key points
- File: a Zig program lives in a text file, and this course names that file main.zig.
- std: std is the standard library, the helpful code that comes with Zig.
- @import: @import loads code from somewhere else, such as std, into your file.
- pub fn main: this line starts main, the function where running begins.
- out: out is a writer, a value that sends text to the screen.
- try: try runs a step and sends an error back to the caller if that step fails.
In this example, the first line imports std, and main then creates the writer called out. The three print calls run in order, so the words appear in order on the screen.
Note
every program in this course keeps this same first shape, so new ideas stand out.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which line marks the starting point of a Zig program?