“consider removing this semicolon” error

2019-01-28 08:59发布

While following the rustbyexample.com tutorial, I typed the following code:

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

And got the following error from the compiler:

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);
  |                                     ^

Why is the semicolon relevant (or not) here?

标签: rust
1条回答
放我归山
2楼-- · 2019-01-28 09:49

The return value from a Rust function is the last expression not followed by a semicolon. With the semicolon, your method doesn't return anything. Without the last semicolon, it returns the value of write!(f, "OMG! {}", self.0).

You can read more about that in The Rust Programming Language chapter about functions; look for the part starting with "What about returning a value?".

查看更多
登录 后发表回答