Skip to content
The Chat Archive
gpt-4.1-mini-2025-04-14· OpenAI LMArena Human Preference 140K

teach me some fundamentals in zig.

  1. User

    teach me some fundamentals in zig.

  2. Assistant

    Absolutely! Zig is a modern, general-purpose programming language designed for robustness, optimality, and clarity. It’s great for systems programming and offers manual memory management, no hidden control flow, and a simple syntax.

    Here are some fundamentals to get you started with Zig:


    1. Hello, World!

    const std = @import("std");
    
    pub fn main() void {
        std.debug.print("Hello, World!\n", .{});
    }
    
    • const std = @import("std"); imports the standard library.
    • pub fn main() void declares the main function, which returns nothing (void).
    • std.debug.print is used for printing formatted output.
    • The .{} is an empty tuple for formatting arguments.

    2. Variables and Constants

    const std = @import("std");
    
    pub fn main() void {
        var x: i32 = 10;       // mutable variable
        const y: f64 = 3.14;   // constant (immutable)
        
        x = 20;                // OK, x is mutable
        // y = 2.71;           // Error, y is constant
        
        std.debug.print("x = {}, y = {}\n", .{x, y});
    }
    
    • var declares a mutable variable.
    • const declares an immutable constant.
    • Types come after the colon (:), e.g., i32 (32-bit signed int), f64 (64-bit float).

    3. Control Flow

    If-else

    const std = @import("std");
    
    pub fn main() void {
        var a: i32 = 5;
    
        if (a > 0) {
            std.debug.print("Positive\n", .{});
        } else if (a == 0) {
            std.debug.print("Zero\n", .{});
        } else {
            std.debug.print("Negative\n", .{});
        }
    }
    

    Loops

    const std = @import("std");
    
    pub fn main() void {
        var i: i32 = 0;
        while (i < 5) : (i += 1) {
            std.debug.print("i = {}\n", .{i});
        }
    }
    
    • The while loop has a post-expression : (i += 1) that runs after each iteration.

    4. Functions

    const std = @import("std");
    
    fn add(a: i32, b: i32) i32 {
        return a + b;
    }
    
    pub fn main() void {
        const result = add(3, 4);
        std.debug.print("3 + 4 = {}\n", .{result});
    }
    
    • Functions are declared with fn.
    • Parameters have types.
    • The return type comes after the parameter list.
    • return returns a value.

    5. Arrays and Slices

    const std = @import("std");
    
    pub fn main() void {
        var arr: [3]i32 = .{1, 2, 3};  // fixed-size array
        var slice: []i32 = arr[0..2];  // slice of the array (elements 0 and 1)
    
        std.debug.print("arr[0] = {}\n", .{arr[0]});
        std.debug.print("slice[1] = {}\n", .{slice[1]});
    }
    
    • [3]i32 is an array of 3 integers.
    • []i32 is a slice (view) into an array.
    • Slices are created with range syntax arr[start..end].

    6. Error Handling

    Zig uses error sets and try for error handling.

    const std = @import("std");
    
    fn mightFail(shouldFail: bool) !void {
        if (shouldFail) {
            return error.Failed;
        }
    }
    
    pub fn main() void {
        const result = mightFail(false);
        if (result) |err| {
            std.debug.print("Error: {}\n", .{err});
        } else {
            std.debug.print("Success!\n", .{});
        }
    }
    
    • !void means the function can return an error or void.
    • return error.Failed; returns an error.
    • You can handle errors with if (result) |err| { ... }.

    7. Structs

    const std = @import("std");
    
    const Point = struct {
        x: i32,
        y: i32,
    };
    
    pub fn main() void {
        var p = Point{ .x = 10, .y = 20 };
        std.debug.print("Point: ({}, {})\n", .{p.x, p.y});
    }
    
    • struct defines a composite data type.
    • You initialize with .field = value.

    Summary

    • Zig is explicit and simple.
    • Use const and var for variables.
    • Functions are declared with fn.
    • Control flow is familiar (if, while).
    • Arrays and slices are distinct.
    • Error handling uses error sets and try.
    • Structs group data.

    If you want, I can help you with more advanced topics like memory management, comptime, or async programming in Zig! Would you like to continue?

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.