gpt4 book ai didi

rust - "consider removing this semicolon"错误

转载 作者:行者123 更新时间:2023-11-29 07:58:19 24 4
gpt4 key购买 nike

同时关注 rustbyexample.com教程中,我输入了以下代码:

impl fmt::Display for Structure {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let x = format!("{}", "something");
write!(f, "OMG! {}", self.0);
}
}

并从编译器中得到以下错误:

error[E0308]: mismatched types
--> src/main.rs:5:58
|
5 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
| __________________________________________________________^
6 | | let x = format!("{}", "something");
7 | | write!(f, "OMG! {}", self.0);
8 | | }
| |_____^ expected enum `std::result::Result`, found ()
|
= note: expected type `std::result::Result<(), std::fmt::Error>`
found type `()`
help: consider removing this semicolon:
--> src/main.rs:7:37
|
7 | write!(f, "OMG! {}", self.0);
| ^

为什么分号在这里相关(或不相关)?

最佳答案

Rust 函数的返回值是最后一个不跟分号的表达式。使用分号,您的方法不会返回任何内容。没有最后一个分号,它返回 write!(f, "OMG! {}", self.0) 的值。

您可以阅读更多相关信息 in The Rust Programming Language chapter about functions ;查找以“如何返回一个值?”开头的部分。

关于rust - "consider removing this semicolon"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30657778/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com