Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. The length of a vector is comptime-known, so I would like to add more information in the compile time error message. @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)),
    }
}
like image 649
loonatick Avatar asked Jul 21 '26 22:07

loonatick


1 Answers

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}
    )
);
like image 67
loonatick Avatar answered Jul 25 '26 10:07

loonatick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!