小编Yiğ*_*alı的帖子

了解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) -> …
Run Code Online (Sandbox Code Playgroud)

function return-type rust

1
推荐指数
1
解决办法
61
查看次数

标签 统计

function ×1

return-type ×1

rust ×1