Skip to content

Incorrect suggestion when assigning Option<T> to a T in a struct pattern #155516

@redlaWw

Description

@redlaWw

Code

fn main() {
    let a: usize;
    
    Thing {
        thing: a
    } = Thing {
        thing: Some(0)
    };
}

struct Thing {
    thing: Option<usize>
}

Current output

error[E0308]: mismatched types
 --> src/main.rs:5:16
  |
2 |     let a: usize;
  |            ----- expected due to this type
...
5 |         thing: a
  |                ^ expected `usize`, found `Option<usize>`
  |
  = note: expected type `usize`
             found enum `Option<usize>`
help: consider using `Option::expect` to unwrap the `Option<usize>` value, panicking if the value is an `Option::None`
  |
5 |         thing: a.expect("REASON")
  |                 +++++++++++++++++

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

Desired output

error[E0308]: mismatched types
 --> src/main.rs:5:16
  |
2 |     let a: usize;
  |            ----- expected due to this type
...
5 |         thing: a
  |                ^ expected `usize`, found `Option<usize>`
  |
  = note: expected type `usize`
             found enum `Option<usize>`

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

Rationale and extra context

Playground Link

The suggestion to use .expect("REASON") on the identifier in the struct pattern is incorrect and doesn't make sense.

Other cases

The same problem is not seen in tuple structs, e.g. the output of the following is fine:

fn main() {
    let a: usize;
    
    Thing(a) = Thing(Some(0));
}

struct Thing(Option<usize>);

Rust Version

version 1.95.0 on the playground.

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions