Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
938 views
in Technique[技术] by (71.8m points)

rust - "consider removing this semicolon" error

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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?".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...