Zig Notes

zig fmt
Login

zig fmt

It's really good and you should always use it. It provides:

  1. Pleasant and uniform (and anonymity-enhancing) code formatting.
  2. The tyrannical oppression that Allman and GNU formatters deserve for their crimes against braces.
  3. Auto-patches to your code around breaking changes in the language.
  4. Fast linting.

But, it can be off-putting, especially until you get more familiar with it.

complaints about zig fmt

formatting examples

const std = @import("std");
const debug = std.debug.print;

test "horizontal without a trailing comma" {
    debug("{any}\n", .{.{ 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1 }});
}

test "vertical with a trailing comma" {
    debug("{any}\n", .{.{
        0,
        10,
        100,
    }});
}

test "aligned matrix with width set by first row (needs trailing comma)" {
    debug("{any}\n", .{.{
        0,   0,   0,   0,
        1,   1,   1,   1,
        10,  10,  10,  10,
        100, 100, 100, 100,
    }});
}

test "manually formatted with trailing comments" {
    debug("{any}\n", .{.{
        0, //
        1, 1, //
        10, 10, 10, //
        100, 100, 100, 100, //
    }});
    // without a trailing comma this formats weirdly.
    // you also can't manually align the comments.
}

test "disabling the formatter (bug)" {
    debug("{any}\n", .{.{
        // zig fmt: off
        0,
        1,               1,
        10,   10,       10,
        100, 100, 100, 100,
        // zig fmt: on
        // ^ oops that does nothing, issue #10418
    }});
}

test "formatter is still off" {
    const
x = 1;
        _ = x;
}
// zig fmt: on

test "indented chains" {
    const msg =
        \\ like so.
        \\
    ;

    const stdout =
        std
        .io
        .getStdout()
        .writer();
    try stdout
        .print(msg, .{});
}

test "linebreaks preserved after operators" {
    if (true and true and true and true) {}
    if (true and
        true and
        true and true and
        true)
    {}
    const sum = 1 +
        2 +
        3 + 4 + 5;
    _ = sum;
}

test "switch details" {
    switch (0) {
        0 => {},

        1, 2 => {},

        3,
        4,
        => {},

        inline 5,
        6,
        => {},

        inline //
        7,
        8,
        => {},

        else => {},
    }
}