Skip to content

Zig Syntax

Syntax is the set of rules for how code has to be written so the compiler understands it. Zig’s rules are small and strict: there’s usually one way to write something, and the compiler tells you right away when you’ve strayed. This page walks through the shape of a Zig file and the handful of rules you’ll bump into in your first week, especially the ones that surprise people coming from C, Python, JavaScript or Rust.

Here’s a small but complete program:

const std = @import("std");
pub fn main() void {
const name = "Zig";
const year = 2016;
std.debug.print("{s} was started in {d}.\n", .{ name, year });
}

Output:

Zig was started in 2016.

Line by line:

  1. const std = @import("std"); loads the standard library and names it std. @import is a builtin function (all builtins start with @). You’ll see this first line in nearly every Zig file.
  2. pub fn main() void { ... } is the function where the program starts. fn starts a function, main is its name, the empty () means it takes no inputs and void means it returns nothing. pub (public) lets code outside this file see it, which Zig needs in order to find main.
  3. const name = "Zig"; creates a constant: a name for a value that won’t change. You’ll meet var for values that change in a moment.
  4. std.debug.print(...) prints text. The dots walk into the library: std, then its debug part, then the print function inside that.

That’s the whole skeleton. Everything else in this tutorial is filling in the middle.

Every statement inside a function ends with ;. Leave one out and Zig stops:

const std = @import("std");
pub fn main() void {
const total = 10
std.debug.print("{d}\n", .{total});
}
main.zig:4:21: error: expected ';' after statement
const total = 10
^

If you’re coming from Python or JavaScript (where semicolons are optional), this will catch you a few times. The caret points to where the ; should go.

Curly braces { } group statements into a block: the body of a function, of an if, of a loop. Indentation is only for people. The compiler doesn’t care about it, but zig fmt will fix it for you.

const std = @import("std");
pub fn main() void {
const temperature = 31;
if (temperature > 30) {
std.debug.print("It's hot.\n", .{});
std.debug.print("Drink some water.\n", .{});
}
if (temperature < 0) std.debug.print("It's freezing.\n", .{});
}

Output:

It's hot.
Drink some water.

The first if runs both lines inside its braces. The second if has a single statement and no braces, which is allowed. Most Zig code uses braces anyway, because it’s easy to add a second line later and forget that it isn’t inside the if.

Notice the round brackets around the condition: if (temperature > 30). In Zig they’re required, like in C and JavaScript (and unlike Python and Rust).

Order of top-level declarations doesn’t matter

Section titled “Order of top-level declarations doesn’t matter”

Things declared at the top level of a file (outside any function) can be used from anywhere in that file, even above where they’re written:

const std = @import("std");
pub fn main() void {
std.debug.print("{d}\n", .{double(21)});
std.debug.print("{s}\n", .{greeting});
}
fn double(n: i32) i32 {
return n * 2;
}
const greeting = "Declared below main, and that's fine.";

Output:

42
Declared below main, and that's fine.

main uses double and greeting before they appear in the file. C programmers will like this: there are no forward declarations and no header files. Inside a function it’s different: there, a name only exists from the line it’s declared on.

double isn’t pub because only this file uses it. fn double(n: i32) i32 reads as “a function named double that takes n, a 32-bit integer, and returns a 32-bit integer”. Functions get their own lesson, Zig Functions.

Zig has two ways to name a value:

  • const for values that never change after you set them.
  • var for values that do. A var needs a type, like : i32.
const std = @import("std");
pub fn main() void {
const max_lives = 3;
var lives: i32 = max_lives;
lives -= 1;
std.debug.print("{d} of {d} lives left\n", .{ lives, max_lives });
}

Output:

2 of 3 lives left

Zig is picky here in a helpful way. If you use var but never change the value, it’s an error, and the compiler tells you to use const:

const std = @import("std");
pub fn main() void {
var count: i32 = 0;
std.debug.print("{d}\n", .{count});
}
main.zig:4:9: error: local variable is never mutated
var count: i32 = 0;
^~~~~
main.zig:4:9: note: consider using 'const'

Use const by default and switch to var only when you need to change something. Zig Variables covers both properly, including why var needs a type.

This one surprises almost everybody. In Zig, an unused local variable isn’t a warning. It’s an error:

const std = @import("std");
pub fn main() void {
const x = 5;
}
main.zig:4:11: error: unused local constant
const x = 5;
^

The same goes for a function’s return value. If a function gives you something back, you have to do something with it:

const std = @import("std");
fn add(a: i32, b: i32) i32 {
return a + b;
}
pub fn main() void {
add(1, 2);
}
main.zig:8:8: error: value of type 'i32' ignored
add(1, 2);
~~~^~~~~~
main.zig:8:8: note: all non-void values must be used
main.zig:8:8: note: to discard the value, assign it to '_'

When you really do want to throw a value away, assign it to _. That tells Zig (and the next person reading your code) that you meant it:

const std = @import("std");
fn add(a: i32, b: i32) i32 {
return a + b;
}
pub fn main() void {
_ = add(1, 2);
std.debug.print("Result thrown away on purpose.\n", .{});
}

Output:

Result thrown away on purpose.

A name (an identifier) starts with a letter or _, followed by letters, digits or _. Names are case-sensitive, so total and Total are different. You can’t use keywords like fn, const or if as names.

The official style guide suggests these conventions, and the standard library follows them:

Kind of thing Style Example
Variables and constants snake_case max_lives, file_name
Functions camelCase double, readFile
Types (structs, enums…) TitleCase Point, ArrayList

There’s an escape hatch for odd names: @"..." lets you use any text as a name, even a keyword or something with spaces. You’ll mostly see it when talking to C libraries, or for names like @"struct" in the standard library. You won’t need it often, but now you’ll recognize it.

Many languages let an inner block reuse a name from outside it. Zig doesn’t:

const std = @import("std");
pub fn main() void {
const x = 1;
{
const x = 2;
std.debug.print("{d}\n", .{x});
}
}
main.zig:6:15: error: local constant 'x' shadows local constant from outer scope
const x = 2;
^
main.zig:4:11: note: previous declaration here
const x = 1;
^

So within a function, each name means one thing. If you’re used to Rust’s let x = x + 1; pattern, pick a new name instead, like x_plus_one. The reference explains this under shadowing.

Habits from other languages that won’t compile

Section titled “Habits from other languages that won’t compile”

A few things you might type out of habit, and what Zig wants instead:

You might write Zig wants Why
a && b, a || b a and b, a or b Zig uses words for logic
i++ i += 1 There’s no ++ or --
'hello' "hello" Single quotes are for one character, like 'h'
/* comment */ // comment Zig only has line comments
print(x) std.debug.print("{d}\n", .{x}) Printing always takes a format string and a .{ } list

Zig’s error messages usually point you straight at the fix. Here’s what && gives you:

const std = @import("std");
pub fn main() void {
const a = 3;
const b = 4;
if (a < b && b < 10) std.debug.print("ok\n", .{});
}
main.zig:6:15: error: ambiguous use of '&&'; use 'and' for logical AND, or change whitespace to ' & &' for bitwise AND
if (a < b && b < 10) std.debug.print("ok\n", .{});
^

And here’s the fixed version:

const std = @import("std");
pub fn main() void {
const a = 3;
const b = 4;
if (a < b and b < 10) std.debug.print("ok\n", .{});
}

Output:

ok

This program was written by someone who usually writes C. Fix it so it compiles and prints count is 1:

const std = @import("std");
pub fn main() void {
var count: i32 = 0;
count++;
if (count > 0 && count < 10) {
std.debug.print("count is {d}\n", .{count})
}
}

Hint: there are three problems. Fix one, run it, read the next error.

Show solution
const std = @import("std");
pub fn main() void {
var count: i32 = 0;
count += 1;
if (count > 0 and count < 10) {
std.debug.print("count is {d}\n", .{count});
}
}

Output:

count is 1

count++ becomes count += 1, && becomes and, and the print line gets its missing ;.

Write a function triple that takes an i32 and returns it times three. Put it below main, and print triple(7) from main.

Hint: copy the shape of double from this page: fn triple(n: i32) i32 { ... }.

Show solution
const std = @import("std");
pub fn main() void {
std.debug.print("{d}\n", .{triple(7)});
}
fn triple(n: i32) i32 {
return n * 3;
}

Output:

21

Top-level declarations can be used anywhere in the file, so main can call triple even though it comes later.

This program doesn’t compile. Change it so it does, without deleting the limit line:

const std = @import("std");
pub fn main() void {
var greeting = "Hi";
const limit = 100;
std.debug.print("{s}\n", .{greeting});
}

Hint: one name should be const, and one value is never used.

Show solution
const std = @import("std");
pub fn main() void {
const greeting = "Hi";
const limit = 100;
_ = limit;
std.debug.print("{s}\n", .{greeting});
}

Output:

Hi

greeting never changes, so it has to be const. limit is never used, so _ = limit; says “I know, that’s on purpose”. In real code you’d usually just delete an unused variable.

  • A Zig file starts with const std = @import("std");, and the program starts at pub fn main() void.
  • Statements end with ;, and braces group them into blocks. Indentation is for humans (and zig fmt).
  • Top-level declarations can be used anywhere in the file, in any order. No forward declarations.
  • Use const by default, var only for values that change.
  • Unused variables and ignored return values are errors. Use _ = to discard on purpose.
  • Names: snake_case variables, camelCase functions, TitleCase types, and no shadowing.
  • Logic uses and / or, and there’s no ++.

Next up: Zig Comments, how to leave notes in your code and write documentation comments.

Quick check

1. You write const x = 5; inside main but never use x. What happens?
2. How do you write "a and b are both true" in Zig?
3. main calls a function helper that is written further down the file, at the top level. Does it compile?
4. Which name follows Zig's style for a type?