Skip to content
Chung Leong edited this page Apr 24, 2024 · 3 revisions

In the Zig language, a function returns void when it has no useful information to return. void is a 0-byte type (akin to an empty struct). It's represented as undefined in JavaScript.

const std = @import("std");

pub fn hello() void {
    std.debug.print("Hello world!\n", .{});
}
import { hello } from './void-example-1.zig';

console.log(hello());
Hello world!
undefined

It's possible to have an array of void:

pub var array_of_nothing: [4]void = .{ {}, {}, {}, {} };
import module from './void-example-2.zig';

console.log(module.array_of_nothing.valueOf());
module.array_of_nothing[3] = undefined;
try {
    module.array_of_nothing[3] = 1;
} catch (err) {
    console.log(err.message)
}
[ undefined, undefined, undefined, undefined ]
Element can only be undefined

void can also appear in structs:

const Sound = struct {
    loud: void = {},
    thunderous: void = {},
    deafening: void = {},
};
const Fury = struct {
    angry: void,
    frenzied: void,
    tempestuous: void,
};
const Tale = struct {
    sound: Sound = .{},
    fury: Fury = .{},
};

pub const Idiot = struct {
    pub fn tell() Tale {
        return .{};
    }
};
import { Idiot } from './void-example-3.zig';

const tale = Idiot.tell();
console.log(tale.valueOf());
console.log(tale.dataView.byteLength);
{
  sound: { loud: undefined, thunderous: undefined, deafening: undefined },
  fury: { angry: undefined, frenzied: undefined, tempestuous: undefined }
}
0

Undefined

Clone this wiki locally