[英]Why can't const functions in Rust make calls to associated functions?
This: 这个:
const fn pow2(exp: u32) -> u32 {
u32::pow(exp, 2)
}
Results in a compiler error: 导致编译器错误:
error[E0015]: calls in constant functions are limited to constant functions, struct and enum constructors
Is there a way to do this? 有没有办法做到这一点?
I'd like to do: 我想做:
pub const MY_BITMASK: u32 = pow2(4);
A const function cannot call a non-const function. const函数不能调用非const函数。 This is because const functions need to be able to run during compilation, so they can't call a non-const function which can only be evaluated at runtime. 这是因为const函数需要能够在编译期间运行,因此它们不能调用只能在运行时求值的非const函数。 Since u32::pow
is not a const function, you can't call it from a const function. 由于u32::pow
不是const函数,因此无法从const函数调用它。
The question now becomes: Why isn't u32::pow
a const function? 现在的问题变成:为什么u32::pow
不是const函数? And the reason for that is a current limitation of const functions: They can only contain a subset of the language. 其原因是const函数的当前限制:它们只能包含该语言的子集。 Notably, they can't contain loops or assignments. 值得注意的是,它们不能包含循环或赋值。 Since u32::pow
uses both of these , it can't be marked as const
and therefore can't be called from const functions. 由于u32::pow
使用了这两种方法 ,因此无法将其标记为const
,因此无法从const函数中调用它。
Note that there isn't any limitation of calling associated functions from const functions, as long as the associated function is marked const
. 请注意,从关联函数调用关联函数没有任何限制,只要关联函数标记为const
。 And u32::pow
is not an associated function in any case: you can call it as eg x.pow(y)
. 而且u32::pow
在任何情况下都不是关联函数:您可以将其称为x.pow(y)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.