我正在尝试创建一个仅接受长度为 4 的内置向量(如
@Vector
)的多态函数。据我了解,向量的长度是 comptime 已知的,我想在编译时错误消息。我知道 @typeName
可用于将类型转换为 comptime 字符串,但是可以用什么来转换 comptime 值呢?
/// 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)),
}
}
Zig 标准库具有
comptimePrint
,用于在 std.fmt
中进行 comptime 字符串格式化(docs)
@compileError(std.fmt.comptimePrint("Not a valid tuple, found a vector of length {}", .{info.len}));