调用"std.math.clamp"会产生编译错误"error:无法计算Zig中的常量表达



为什么这个程序编译失败?Zig版本0.6.0。

const std = @import("std");
fn get_value () f32 {
return 1.0;
}
test "testcase" {
const value: f32 = 1. + get_value() ;
_ = std.math.clamp(value, 0.0, 255.0);
}

给出编译错误:

$ zig test src/clamp.zig       
Semantic Analysis [790/1017] ./src/clamp.zig:9:24: error: unable to evaluate constant expression
_ = std.math.clamp(value, 0.0, 255.0);
^
./src/clamp.zig:9:23: note: referenced here
_ = std.math.clamp(value, 0.0, 255.0);
^

原因是value与常量0.0255.0的类型不同。valuef32,常数的类型是comptime_float

修复方法是将常量强制转换为f32

_ = std.math.clamp(value, @as(f32, 0.0), @as(f32, 255.0));

clamp类型似乎要求所有参数要么是comptime值,要么都是运行时值。

请参阅https://ziglearn.org/chapter-1/#comptime

最新更新