githubEdit

Language Basics

The basics of the Zig language are quite straightforward. Given here are examples of each basic concept, which should be picked up and experimented upon.

circle-info

For code examples that don't define a mainfunction, please define your own mainfunction and paste the code inside in order to run it.

Hello, world!

We have to import the standard library here using @import("std"), which we then store in the stdvariable. We can access functions (and types) from the standard library using the .syntax.

const std = @import("std");

pub fn main() !void {
    std.debug.print("Hello, world!\n", .{});
}

Primitives

// ints
const my_32_bit_int: i32 = -42;
const my_64_bit_int: i64 = -323;
const my_32_bit_unsigned_int: u32 = 3424;
const my_64_bit_unsigned_int: u64 = 34;

// more ints ...?
const my_17_bit_int: i17 = 17;
const my_38_bit_unsigned_int: i38 = 38;

// floats
const my_32_bit_float: f32 = 3.14;
const my_64_bit_float: f64 = 3.14159;

// bool
const my_bool: bool = true;

// string
const my_string: []const u8 = "Hello, world!";

std.debug.print("32-bit int: {}\n", .{my_32_bit_int});
std.debug.print("64-bit int: {}\n", .{my_64_bit_int});
std.debug.print("32-bit unsigned int: {}\n", .{my_32_bit_unsigned_int});
std.debug.print("64-bit unsigned int: {}\n", .{my_64_bit_unsigned_int});
std.debug.print("17-bit int: {}\n", .{my_17_bit_int});
std.debug.print("38-bit unsigned int: {}\n", .{my_38_bit_unsigned_int});
std.debug.print("32-bit float: {}\n", .{my_32_bit_float});
std.debug.print("64-bit float: {}\n", .{my_64_bit_float});
std.debug.print("bool: {}\n", .{my_bool});
std.debug.print("string: {s}\n", .{my_string});

Arrays, Pointers & Slices

Arrays

Arrays in Zig have a fixed size (defined in the type of the array). There aren't many differences between Zig arrays and those found in C, C++, Java or Go besides syntax.

Pointers

Zig defines two kind of pointers: pointers to a single value, and pointers to multiple values. This is a departure from C and C++, where a pointer to an array with 1000000 integer looks the same as a pointer to a single integer (int*).

circle-info

Notice that the [*:0]u8type is perfect for representing strings in C, since they terminate in \0and we keep track of a pointer to their first character.

Slices

Control Flow

If/else

Switch

While

For

Structs

Enums

Unions

Unions allow you to store one of their members at a time, instead of all at once like in a struct. Zig unions can be treated similarly to C unions, except that they do throw a runtime error if you access the incorrect member (at the cost of a larger runtime size due to storing extra info).

Functions

Optionals

Last updated