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. 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.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. Sinceu32::pow
uses both of these, it can't be marked asconst
and therefore can't be called from const functions.Note that there isn't any limitation of calling associated functions from const functions, as long as the associated function is marked
const
. Andu32::pow
is not an associated function in any case: you can call it as e.g.x.pow(y)
.