Expected `!`, found `()`

How to fix it?

fn main()->! {
    let mut s= String::from("ss");
    s.push_str("gg");
    println!("{}",s);
}

(Playground)

Errors:

   Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
 --> src/main.rs:1:12
  |
1 | fn main()->! {
  |    ----    ^ expected `!`, found `()`
  |    |
  |    implicitly returns `()` as its body has no tail or `return` expression
  |
  = note:   expected type `!`
          found unit type `()`

For more information about this error, try `rustc --explain E0308`.
error: could not compile `playground` due to previous error

Seems, this guy does not have any problems...

Don’t believe all code you see in a YouTube video is correct and/or tested.[1]

One doesn’t even need to scroll down through all that many other comments (some of which are also pointing out other code examples that don’t actually compile, or explanations that aren’t completely accurate) to find someone already pointing out this exact mistake…


Put simply, the type signature fn main()->! means that “the main function will never terminate”. Either because of an infinite loop, or because of a panic, or because a different non-terminating function is called. The ->! means that the main function will (be required to) unconditionally/definitely do any of these things, instead of terminating/returning.

On the other hand, the body of the main function here does (well… at least can) terminate/return. So the way to fix it is

  • either change the implementation, e.g. by inserting some infinite loop or panic at the end
  • or perhaps fn main()->! isn’t what you wanted in the first place, so fix the signature and remove that “->!”!

  1. I suppose instances like this, where people go through all the effort of writing a script, fancily rendering and neatly animating some code that ought to be runnable without ever testing it, can serve as a good demonstration of just how valuable a feature it is that code snippets in rustdoc can/are automatically tested, even besides the additional “make sure that the examples in the API docs don’t go out of sync with the actual API implementation” argument that applies there, too. ↩︎

8 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.