Quick Start Guide
This guide will help you write, build, and run your first Zig program.Hello, World!
Let’s start with the classic “Hello, World!” program.Write the code
Add the following code from test/standalone/simple/hello_world/hello.zig:1-5:Let’s break down what this code does:
hello.zig
const std = @import("std");- Import Zig’s standard librarypub fn main() !void- Define a public main function that may return an errortry- Unwrap the error union, returning early if an error occursstd.fs.File.stdout().writeAll()- Write to standard output
Building an Executable
To create a standalone executable, usezig build-exe:
Optimization Modes
Control the optimization level:- Debug: Full safety checks, no optimization (default)
- ReleaseFast: Optimized for speed, safety checks disabled
- ReleaseSmall: Optimized for binary size
- ReleaseSafe: Optimized for speed, safety checks enabled
A More Interactive Example
Let’s create a simple number guessing game from test/standalone/simple/guess_number/main.zig:1-36:guess_number.zig
- Reading from standard input
- Using the standard library’s random number generation
- Error handling with
catch - String parsing and manipulation
- Control flow with
whileloops
Creating a Project with Build System
For larger projects, use Zig’s build system:Initialize a new project
build.zig- Build configurationbuild.zig.zon- Package metadatasrc/main.zig- Main source filesrc/root.zig- Library root (optional)
Examine the build file
The
build.zig file defines your build process. It’s written in Zig, similar to build.zig:1:Cross-Compilation
One of Zig’s superpowers is effortless cross-compilation:Common Commands
Here are the most frequently used Zig commands:| Command | Description |
|---|---|
zig run <file> | Compile and run a Zig file |
zig build-exe <file> | Compile to executable |
zig build-lib <file> | Compile to library |
zig build-obj <file> | Compile to object file |
zig build | Build using build.zig |
zig test <file> | Run tests in a file |
zig fmt <file> | Format Zig source code |
zig init | Initialize a new project |
zig version | Show Zig version |
zig zen | Display the Zen of Zig |
zig targets | List compilation targets |
Error Handling Example
Zig’s error handling is explicit and compile-time verified:The
! in the return type indicates the function may return an error. Use try to propagate errors or catch to handle them.Next Steps
Now that you’ve built your first Zig programs, continue learning:Language Guide
Deep dive into Zig’s syntax and features
Standard Library
Explore Zig’s standard library
Build System
Master the Zig build system
Language Reference
Complete language reference
Getting Help
If you get stuck:- Read the language reference
- Join the Zig community
- Check zig.guide for tutorials
- Ask questions on the Zig forum