In the following article I saw the following:
A const fn allows you to execute code in a "const context." For example:
const fn five() -> i32 {
5
}
const FIVE: i32 = five();
What does const fn exactly do in rust? Does it just say that the function can be completely be calculated at compile time (my guess based on reading the article)
Some expressions, called constant expressions, can be evaluated at compile time. In const contexts, these are the only allowed expressions, and are always evaluated at compile time. In other places, such as let statements, constant expressions may be, but are not guaranteed to be, evaluated at compile time.
The obvious question is, which expressions are guaranteed to be evaluated at compile time. They are:
A const fn is a function that one is permitted to call from a const context. When called from a const context, the function is interpreted by the compiler at compile time. The interpretation happens in the environment of the compilation target and not the host. So usize is 32 bits if you are compiling against a 32 bit system, irrelevant of whether you are building on a 64 bit or a 32 bit system.
Const functions have various restrictions to make sure that they can be evaluated at compile-time. It is, for example, not possible to write a random number generator as a const function. Calling a const function at compile-time will always yield the same result as calling it at runtime, even when called multiple times.
For more details, see here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With