为什么 Rust 中的 const 函数不能调用关联函数? [英] Why can't const functions in Rust make calls to associated functions?
问题描述
这个:
const fn pow2(exp: u32) -> u32 {
u32::pow(exp, 2)
}
导致编译器错误:
error[E0015]: calls in constant functions are limited to constant functions, struct and enum constructors
有没有办法做到这一点?
Is there a way to do this?
我想做:
pub const MY_BITMASK: u32 = pow2(4);
推荐答案
const 函数不能调用非常量函数.这是因为 const 函数需要能够在编译期间运行,因此它们不能调用只能在运行时评估的非常量函数.由于 u32::pow
不是 const 函数,所以不能从 const 函数调用它.
A const function cannot call a non-const function. 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. Since u32::pow
is not a const function, you can't call it from a const function.
现在的问题变成:为什么 u32::pow
不是 const 函数?其原因是 const 函数的当前限制:它们只能包含语言的一个子集.值得注意的是,它们不能包含循环或赋值.由于 u32::pow
使用了这两个,它不能被标记为const
,因此不能被const函数调用.
The question now becomes: Why isn't u32::pow
a const function? And the reason for that is a current limitation of const functions: They can only contain a subset of the language. 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.
请注意,从 const 函数调用关联函数没有任何限制,只要关联函数标记为 const
.并且 u32::pow
在任何情况下都不是关联函数:您可以将其称为例如x.pow(y)
.
Note that there isn't any limitation of calling associated functions from const functions, as long as the associated function is marked const
. And u32::pow
is not an associated function in any case: you can call it as e.g. x.pow(y)
.
更新: Const 函数 获得更多可以在 Rust 1.46 中使用的语言特性(包括 if
、while
、&&
、等),并且整数类型的 pow
函数在 Rust 1.50.
Update: Const functions gained a lot more language features they can use in Rust 1.46 (including if
, while
, &&
, etc.), and the integer types' pow
functions were made const
in Rust 1.50.
这篇关于为什么 Rust 中的 const 函数不能调用关联函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!