What is `const fn`?


I have found const fn function somewhere on stackoverflow recently but I don’t remember seeing it in the rust-book or anywhere else. What is it, what are use cases?


It is a function which can be evaluated at compile time, conceptually similar to constexpr functions in C++. That is currently a nightly-only feature, although work has begun on stabilizing calls to const fns. The name comes from the fact that you can assign the result of a const fn to a const.

There are two broad use cases. One is to make sure that the compiler can pre-compute some quantities at compilation time when that is necessary for good run-time performance. The other is to derive quantities which have to be known at compile time, such as the length of arrays.


Any time you see an unstable feature, you can go to https://doc.rust-lang.org/nightly/unstable-book/ and find out at least something about it.

In this case, that’s this page: https://doc.rust-lang.org/nightly/unstable-book/language-features/const-fn.html

It also points to the tracking issue: https://github.com/rust-lang/rust/issues/24111

which points to the RFC: https://github.com/rust-lang/rfcs/pull/911

It’s true that these aren’t the best possible docs, but since we’re still working on stable things, we don’t always take a ton of time to document unstable features.