Search code examples
stringformattingmetaprogrammingzig

Formating strings with comptime values in Zig


I am trying to create a polymorphic function that accepts only built-in vectors (as in @Vector) of length 4. From what I understand, the length of vectors are comptime known, and I would like to add more information in the compile time error message. I know that @typeName can be used to convert types to comptime strings, but what can one use for comptime values?

/// v[3] == 1
/// v must be a built-in vector of length 4
pub fn ispoint(v: anytype) bool {
    const T = @TypeOf(v);
    switch (@typeInfo(T)) {
        .Vector => |info| {
            if (info.len != 4) {
                // TODO: report length of provided argument
                @compileError("Not a valid tuple, found Vector of length ???");
            }
            return v[3] == 1;
        },
        else => @compileError("`ispoint` expected a `@Vector(4, T)`, found " ++ @typeName(T)),
    }
}

Solution

  • The Zig standard library has comptimePrint for comptime string formating in std.fmt (docs)

    @compileError(std.fmt.comptimePrint("Not a valid tuple, found a vector of length {}", .{info.len}));