Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Q7: return not use ; #10

Open
yangwenmai opened this issue Apr 29, 2019 · 0 comments
Open

Q7: return not use ; #10

yangwenmai opened this issue Apr 29, 2019 · 0 comments
Labels
question Further information is requested

Comments

@yangwenmai
Copy link
Owner

函数返回结果 Result 不能用

否则报错:

error[E0308]: mismatched types
  --> src/main.rs:94:27
   |
94 | fn run(config: Config) -> Result<(), Box<dyn Error>> {
   |    ---                    ^^^^^^^^^^^^^^^^^^^^^^^^^^ expected enum `std::result::Result`, found ()

从提示应该很明显了,但是我看这个提示一直想了很久/尝试了很多次,都没有改正确,我还怀疑是中文文档的问题。

去查英文 tutorial 对应这个例子,结果突然看到了 Ok(()) 是没有 ;,我才记起来。

在实践中,Rust 语法期望语句后面跟其他语句。这意味着用分号来分隔各个表达式。
这意味着 Rust 看起来很像大部分其他使用分号作为语句结尾的语言,并且你会看到分号出现在几乎每一行 Rust 代码。

那么我们说“几乎”的例外是什么呢?比如:

fn add_one(x: i32) -> i32 {
    x + 1;
}

我们的函数声称它返回一个 i32,不过带有一个分号的话,它将返回一个 ()。Rust 意识到这可能不是我们想要的,并在我们看到的错误中建议我们去掉分号:

@yangwenmai yangwenmai added the question Further information is requested label Apr 29, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

1 participant