zig fmt

zig fmt formats Zig source files consistently. Here’s some poorly formatted code:

const std=@import( "std" );

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

zig fmt changes the file to follow Zig conventions:

$ zig fmt zig-fmt.zig
zig-fmt.zig
$ cat zig-fmt.zig
const std = @import("std");

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

zig fmt intentionally doesn’t have any configuration options to change how code is formatted.

However, there are a couple of case where we can guide it with the code itself. For function calls, if there’s a comma after the last argument, zig fmt will put each argument on a separate line:

fn f(a: u64, b: u64, c: u64) void {
    _ = a;
    _ = b;
    _ = c;
}

pub fn main() void {
    f(1, 2, 3);
    f(1, 2, 3, );
}
$ zig fmt zig-fmt-2.zig
zig-fmt-2.zig
$ cat zig-fmt-2.zig
fn f(a: u64, b: u64, c: u64) void {
    _ = a;
    _ = b;
    _ = c;
}

pub fn main() void {
    f(1, 2, 3);
    f(
        1,
        2,
        3,
    );
}

For array initialization, it’ll also look at the number of values on the first line and align all values vertically:

pub fn main() void {
    const matrix: [_]u64 = .{
        1,2,3,
        4,5,6,7,8,9,10,11,12,
    };
    _ = matrix;
}
$ zig fmt zig-fmt-3.zig
zig-fmt-3.zig
$ cat zig-fmt-3.zig
pub fn main() void {
    const matrix: [_]u64 = .{
        1,  2,  3,
        4,  5,  6,
        7,  8,  9,
        10, 11, 12,
    };
    _ = matrix;
}

The convention in the Zig community is to use zig fmt for all source code. Most of us have our editor set up to run it automatically.

Next example: zig build.