Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...