Void vs {}

Note: I’m using Zig 0.13.0

After trying this:

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

pub fn main() void {
    print("{any}\n", .{10});
    print("{any}\n", .{@TypeOf(10)});

    print("{any}\n", .{void});
    print("{any}\n", .{{}});
    print("{any}\n", .{@TypeOf({})});
}

The output is:

10
comptime_int
void
void
void

So what is the difference between “void” and “{}”?

I ask this because this code is valid:

    std.mem.sort(T, data, {}, comptime std.sort.asc(T));

Meanwhile this code is invalid:

    std.mem.sort(T, copy, void, comptime std.sort.asc(T));
``

I believe that void is a type with size zero, while {} is an “instance of the void type.”

pub fn main() void {
    @compileLog(@TypeOf(void));
    @compileLog(@TypeOf({}));
}
Compile Log Output:
@as(type, type)
@as(type, void)
10 Likes

void is a more-or-less regular type. It’s defined to be 0 bits and is instantiated implicitly when you return from a function or block that returns void.
You can instantiate void explicitly with void{}.

const a: void = void{}; // instantiate void
const b: void = {}; // execute a block that returns void implicitly

You’ll see {} more often than void{} because it’s less to type, but it’s a matter of taste.

7 Likes