为什么这个程序编译失败?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.0
和255.0
的类型不同。value
是f32
,常数的类型是comptime_float
。
修复方法是将常量强制转换为f32
。
_ = std.math.clamp(value, @as(f32, 0.0), @as(f32, 255.0));
clamp类型似乎要求所有参数要么是comptime值,要么都是运行时值。
请参阅https://ziglearn.org/chapter-1/#comptime