Why does this program fail to compile? Zig version 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);
}
Gives compile error:
$ 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);
^
The reason is that
value
has different type than the constants0.0
and255.0
.value
isf32
, and the type for the constants iscomptime_float
.The fix is to cast the constants to
f32
.Type of clamp seems to require that all parameters are either comptime values, or all are runtime values.
See https://ziglearn.org/chapter-1/#comptime