7

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)),
    }
}

1 Answer 1

12

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}
    )
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.