问题描述
为什么该程序无法编译? 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,255.0);
^
./src/clamp.zig:9:23: note: referenced here
_ = std.math.clamp(value,255.0);
^
解决方法
原因是value
与常量0.0
和255.0
的类型不同。
value
是f32
,常量的类型是comptime_float
。
解决方法是将常量转换为f32
。
_ = std.math.clamp(value,@as(f32,0.0),255.0));
钳位类型似乎要求所有参数要么都是comptime值,要么全部是运行时值。