我是 rust 的新手(来自 c/c++ 和 python 编程)所以为了学习我正在编写一些基本函数。下面我有一个阶乘函数,它接受一个有符号整数,并且有两个 if 检查它。
fn factorial(x: i32) -> i32 {
let result = if x > 1 {
x * factorial(x-1)
} else if x <= 1 {
1
};
result
}
Run Code Online (Sandbox Code Playgroud)
据我所知,if 和 else-if 块应该处理它的所有情况。但是,在编译时会引发以下错误:
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 `()`, …Run Code Online (Sandbox Code Playgroud) rust ×1