Why match needs explicit reference conversion?

Consider these codes:

    let x = "hello".to_string();
    match &x {
        "hello" => {println!("{}", x)},
        _ => {}

The compiler would throw error::

6 |     match &x {
  |           -- this expression has type `&String`
7 |         "hello" => {println!("{}", x)},
  |         ^^^^^^^ expected struct `String`, found `str`

Why it failed to do auto deref to &str? When I replace match &x with match &*s, it would ok then.

That's just not a place in which Rust performs deref coercions. It's been suggested before to allow this - see Issue 28606 - but it would require an RFC, which no-one has gone forward and proposed yet.


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.