I'm new to rust (coming from programming in c/c++ and python) so to learn I'm writing some basic functions. Below I have a factorial function that takes in a signed integer and has two if checks for it.
fn factorial(x: i32) -> i32 {
let result = if x > 1 {
x * factorial(x-1)
} else if x <= 1 {
1
};
result
}
To my knowledge, the if and else-if blocks should handle every case for it. However, when compiling it throws the following error:
error[E0317]: `if` may be missing an `else` clause
--> src/main.rs:22:12
|
22 | } else if x <= 1 {
| ____________^
23 | | 1
| | - found here
24 | | };
| |_____^ expected `()`, found integer
|
= note: `if` expressions without `else` evaluate to `()`
= help: consider adding an `else` block that evaluates to the expected type
error: aborting due to previous error
For more information about this error, try `rustc --explain E0317`.
error: could not compile `functions`
If I replace the else-if with just an else, it compiles just fine. Why do I need to replace it with an else? Shouldn't the previous else-if be good enough?