"考虑删除这个分号"错误

时间:2015-06-05 03:12:10

标签: rust

在遵循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);
  |                                     ^

为什么分号在这里是否相关?

1 个答案:

答案 0 :(得分:5)

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

的值

您可以详细了解in The Rust Programming Language chapter about functions;寻找以“返回值怎么样?”开头的部分。