调用`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,255.0);
                       ^
./src/clamp.zig:9:23: note: referenced here
    _ = std.math.clamp(value,255.0);
                      ^

解决方法

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

解决方法是将常量转换为f32

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

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

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...