Yiğ*_*alı 1 function return-type rust
我正在尝试通过从书中学习Rust来学习它。最常见的事情是有趣的添加。我尝试编写一些代码以适应它,所以我决定按照本章的说明进行操作,并编写一个快速的斐波那契函数,但是出现错误,我无法解决问题。任何防锈专家都会向我解释为什么会发生这种情况及其背后的逻辑。
fn fibo(x: i32) -> i32 {
if x == 0 {
0
}
else if x == 1 {
1
}
fibo(x-1) + fibo(x-2)
}
Run Code Online (Sandbox Code Playgroud)
当我尝试构建此代码时,出现以下错误;
error[E0308]: mismatched types
--> src/main.rs:6:9
|
6 | 0
| ^ expected (), found integer
|
= note: expected type `()`
found type `{integer}`
error[E0308]: mismatched types
--> src/main.rs:9:9
|
9 | 1
| ^ expected (), found integer
|
= note: expected type `()`
found type `{integer}`
Run Code Online (Sandbox Code Playgroud)
但是,如果我将代码更改为以下代码,则效果很好;
fn fibo(x: i32) -> i32 {
if x == 0 {
0
}
else if x == 1 {
1
}else{
fibo(x-1) + fibo(x-2)
}
}
Run Code Online (Sandbox Code Playgroud)
在Rust语言书中,声明了编译器检查if-else块中所有表达式的类型,但也声明如果不存在else语句,它将传递到下一行代码。既然我说过返回类型将是i32,那么为什么编译器可以期望错误中看到类型“()”?
这里的问题是,您正在尝试具有两个“ return”语句。
当块的最后一个语句缺少分号时,该语句的结果就是评估整个块的类型。在伪锈中,我们可以说以下
{
0
} -> usize
Run Code Online (Sandbox Code Playgroud)
那就是说
let x = { 0 };
Run Code Online (Sandbox Code Playgroud)
为产生一个新的作用域0,因为该块中没有分号,所以隐式返回它,然后成为该块的类型。因此,x: usize。
发生什么了?
您的代码有两个隐式返回:
fn fibo(x: i32) -> i32 {
if x == 0 { // This starts a block
0 // First implicit return
}
else if x == 1 { // This also starts a block
1 // First implicit return
} // Therefore this entire if/else statement is an implicit return unless its output
// is suppressed with a semicolon.
fibo(x-1) + fibo(x-2) // Here we try to return again, which confuses rust!
}
Run Code Online (Sandbox Code Playgroud)
因为您if/else包含隐式返回并且未分配给变量,所以就像我说以下内容一样:
fn fibo(x: i32) -> i32 {
//For the sake of explanation, let's assume x == 0
0 // instead of your if/else
fibo(x-1) + fibo(x-2)
}
Run Code Online (Sandbox Code Playgroud)
不好了!如何解决这个问题:
fn fibo(x: i32) -> i32 {
if x == 0 {
// return 0; // This is an early return; this will break until it reaches the function
0 // Since this is about implicit returns I'll use them here
} else if x == 1 {
1
} else {
fibo(x - 1) + fibo(x - 2)
}
}
Run Code Online (Sandbox Code Playgroud)