Is it possible to have a recursive function computed at compile-time in Rust?

This is currently explored under the feature const_fn, but for now you cannot call a function, even const, from another const function.

You can however break out the big guns: metaprogramming (procedural macro) to compute the value at compile-time. I found this crate for example (but did not test it, though).

This Rosetta Code page on compile time calculation shows that the compiler can do some compile-time optimization, but nothing is guaranteed, and this is only a particular case.


Since your original question, Rust has been updated and now supports conditionals in const fn, so the first two solutions work. See the Const functions section in the Rust Reference which states that you can have "Calls to other safe const functions (whether by function call or method call)" in const functions.

For your particular factorial example, you have (at least) a couple options. Here is a factorial function that I have successfully compiled:

const fn factorial(n: u64) -> u64 {
    match n {
        0u64 | 1u64 => 1,
        2u64..=20u64 => factorial(n - 1u64) * n,
        _ => 0,
    }
}

Note, n! where n > 20 will overflow a u64, so I decided to return 0 in that case. Also, since usize could be a 32-bit value, I explicitly use the 64-bit u64 in this case. Handling the u64 overflow case also prevents the stack overflow. This could return an Option<u64> instead:

const fn factorial(n: u64) -> Option<u64> {
    match n {
        0u64 | 1u64 => Some(1),
        2u64..=20u64 => match factorial(n - 1u64) {
            Some(x) => Some(n * x),
            None => None,
        },
        _ => None,
    }
}

In my case, returning an Option<u64> limited how I could use the function, so I found it more useful to just return a u64 with 0 as the analogue to None.