Hello World in Zig
Your first Zig program - the classic Hello World example with Docker setup
Every programming journey starts with Hello World. Let’s write our first Zig program.
The Code
Create a file named hello.zig:
| |
Understanding the Code
const std = @import("std")- Imports Zig’s standard library@import- A built-in function (prefixed with@) for importing modulespub fn main() !void- Declares the entry point;!voidmeans it can return an error or voidstd.io.getStdOut().writer()- Gets a writer for standard outputtry- Propagates any error from the write operationstdout.print- Writes formatted output to stdout"Hello, World!\n"- The format string with a newline.{}- An empty anonymous struct (required for formatting arguments)
Running with Docker
The easiest way to run this without installing Zig locally:
| |
Running Locally
If you have Zig installed:
| |
Expected Output
Hello, World!
Key Concepts
- Standard library import - Nearly all Zig programs start with
@import("std") - Built-in functions - Prefixed with
@, like@import,@intCast, etc. pubkeyword - Makes functions and variables visible outside the module- Format strings - Similar to printf but with compile-time type checking
- Anonymous structs -
.{}syntax is used for passing arguments
Alternative: Using Debug Print
For quick debugging, you can use std.debug.print, which writes to stderr:
| |
Key differences:
void- No error handling needed (debug print doesn’t return errors)- No
try- Debug print handles errors internally - Writes to stderr - Useful for debugging but not for normal program output
Understanding Error Handling
Zig has explicit error handling. The !void return type means:
| |
This is fundamental to Zig’s philosophy of making everything explicit.
Compilation Options
Zig offers several build modes:
| |
Cross-Compilation
One of Zig’s killer features is easy cross-compilation:
| |
More Verbose Version
Here’s a version that shows more Zig concepts:
| |
This demonstrates:
[]const u8- Zig’s string type (a slice of constant bytes)comptime- Operations performed at compile time++- Array concatenation operator{s}- Format specifier for string slices
Why Zig for Hello World?
Even this simple program demonstrates Zig’s design philosophy:
- Explicit imports - No implicit global namespace
- Clear entry point -
pub fn main()with visible return type - No hidden magic - Every operation is visible in the code
- Error awareness - Even basic I/O considers error handling
Next Steps
Continue to Variables and Data Types to explore Zig’s type system, including integers of any bit width, optionals, and comptime type introspection.
Running Today
All examples can be run using Docker:
docker pull euantorano/zig:master