Formating strings with comptime values in Zig
Asked Answered
B

1

7

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)),
    }
}
Brooke answered 7/4, 2023 at 10:3 Comment(0)
B
10

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}));
Brooke answered 12/4, 2023 at 10:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.