recursionrusttypesparametersfactorial

Recursion, Parameter & Return Types


How can the input parameter n be changed to i8 and this code still work?

fn fact(n: i128) -> i128 {
    if n != 1 { n * fact(n - 1) } else { 1 }
}

Solution

  • Cast n to i128 in the necessary place:

    fn fact(n: i8) -> i128 {
        if n != 1 { i128::from(n) * fact(n - 1) } else { 1 }
    }