Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rust const fn what does it exactly mean

Tags:

constants

rust

Rust const fn

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)

like image 879
Willem van der Veen Avatar asked Nov 29 '25 21:11

Willem van der Veen


1 Answers

To understand const fn you first need to understand const expressions.

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:

  • Array type length 1, array repeat length 2
  • Initialiser of constants 3, statics 4, enum discriminants 5
  • Const generic arguments 6
So now, what is a const fn:

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.

like image 183
Patrick Avatar answered Dec 02 '25 13:12

Patrick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!