Why can't const functions in Rust make calls t

2020-04-30 10:11发布

问题:

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);

回答1:

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. Since u32::pow uses both of these, it can't be marked as const 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. And u32::pow is not an associated function in any case: you can call it as e.g. x.pow(y).



标签: static rust