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

I want to calculate factorial a const. I want to get something like this:

const N: usize = 4;
const N_PERMUTATIONS = factorial(N);

Obvious solutions (which do not work):

  • const fn- conditional statements are not allowed (or at least not implemented) in const fn, none of the following will compile:

    const fn factorial(n: usize) -> usize {
        match n {
            0 => 1,
            _ => n * factorial(n-1)
        }
    }
    
    const fn factorial(n: usize) -> usize {
        if n == 0 {
            1
        } else {
            n * factorial(n-1)
        }
    }
    
  • macros - expression evaluations are performed after all macro extensions. This macro will never reach the base case, because after four iterations an argument 4-1-1-1-1that does not match 0:

    macro_rules!factorial {
        (0) => (1);
        ($n:expr) => ($n * factorial($n-1));
    }
    

I also tried the following, which will work if it *evaluates a short circuit, but as-is has unconditional recursion that gives a stack overflow:

const fn factorial(n: usize) -> usize {
    ((n == 0) as usize) + ((n != 0) as usize) * n * factorial(n-1)
}

( ., factorial(n - ((n != 0) as usize)).)

.

+5
1

const_fn, , const, const.

: ( ) . , ( , ).

Rosetta , , , .

+3

Source: https://habr.com/ru/post/1678836/


All Articles