在Zig中使用comptime值格式化字符串

3

我正在尝试创建一个多态函数,它只接受长度为4的内置向量(如@Vector)。据我所知,向量的长度是在编译时已知的,我想在编译时错误消息中添加更多信息。我知道@typeName可以用于将类型转换为编译时字符串,但对于编译时值,有什么可以使用的吗?

/// x[3] == 1
/// x must be a built-in vector of length 4
pub fn ispoint(x: 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个回答

4

Zig标准库中的comptimePrint用于在std.fmt中进行编译时字符串格式化(docs)。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接