Better diagnostic informations for match an `Option<String>` with `Option<&str>`

When I tried

match std::env::args().nth(1) {
    Some("foo") =>(),
    _ => ()
}

A very disappointed information occurs:

error[E0308]: mismatched types
 --> test.rs:3:10
  |
2 | match std::env::args().nth(1) {
  |       ----------------------- this expression has type `Option<String>`
3 |     Some("foo") =>(),
  |          ^^^^^ expected `String`, found `&str`

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0308`.

The correct version should be

match std::env::args().nth(1).as_deref() {
    Some("foo") =>(),
    _ => ()
}

It takes a lot of time to figure out what the correct function is:

std::env::args().nth(1).as_ref() // Got Option<&String>, but not Option<&str>
std::env::args().nth(1).map(|x|&x) // trying map Option<String> to Option<&str>, but failed since `returns a value referencing data owned by the current function` is not allowed
std::env::args().nth(1).as_ref().map(|x|x.as_str()) // if `as_deref` does not came into mind, this should be the only way.

All the methods are not easy directly enough, thus we may need another error messsage about that, to tell the users how to match an Option<String> with Option<&str>.

Same things may happened to something like Result<String, String>, either.

10 Likes