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?

5 Likes

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.

19 Likes

Any time you see an unstable feature, you can go to The Unstable Book - The Rust 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.

13 Likes

So is const fn essentially marking a function as "pure"?

I got this idea from another comment ... and I'd be really happy to see support for pure functions. I.e., functions with referential transparency, where it always returns the same output for a given input. The RFC and Issues seem to imply this, but I'm not sure.

7 Likes

Yes.

2 Likes

I think i had a problem with this too:

trying to assign the return values of a normal (non const) function to a constant results in compiler error :frowning:

And generic const. functions are not supported (because type size has to be predefined??).

Actually it's because count_searchvalue isn't const, and even if you try, you will end up with generic problems because generic const fns aren't stable:

error: trait bounds other than `Sized` on const fn parameters are unstable
  --> src/lib.rs:20:28
   |
20 | const fn count_searchvalue<T: std::cmp::PartialEq>(tofind: &T, gamemap: &[T])->usize{
   |                            ^

and this is furthered by the fact that there is a call to a non-const function iter in count_searchvalue. Even if you take away the call to count_searchvalue and replace it with a constant, you end up with a plethora of problems in your other function that isn't really structured in a way to support consting it.