Skip to content

Suggest dereferencing boxed enum when matching #57741

Description

@estebank

Given the following code:

enum E {
A(usize),
B(usize),
}
fn main() {
let x = Box::new(E::A(3));
let y = match x {
E::A(a) | E::B(a) => a,
};
}

the compiler outputs:

error[E0308]: mismatched types
--> src/main.rs:9:9
|
8 | let y = match x {
| - this match expression has type `std::boxed::Box<E>`
9 | E::A(a) | E::B(a) => a,
| ^^^^^^^ expected struct `std::boxed::Box`, found enum `E`
|
= note: expected type `std::boxed::Box<E>`
found type `E`
error[E0308]: mismatched types
--> src/main.rs:9:19
|
8 | let y = match x {
| - this match expression has type `std::boxed::Box<E>`
9 | E::A(a) | E::B(a) => a,
| ^^^^^^^ expected struct `std::boxed::Box`, found enum `E`
|
= note: expected type `std::boxed::Box<E>`
found type `E`

Adding changing line 8 to let y = match *x { makes the code compile correctly (partly thanks to match ergonomics, I believe).

The error message would ideally be closer to

error[E0308]: mismatched types
--> src/main.rs:9:9
|
8 | let y = match x {
| -
| |
| this match expression has type `std::boxed::Box<E>`
| help: dereference the boxed value: `*x`
9 | E::A(a) | E::B(a) => a,
| ^^^^^^^ ^^^^^^^ expected struct `std::boxed::Box`, found enum `E`
| |
| expected struct `std::boxed::Box`, found enum `E`
|
= note: expected type `std::boxed::Box<E>`
found type `E`

Adding the suggestion should be relatively easy, condensing the multiple alternative match arm discriminants with mismatched type errors into one might be more involved.


@nikomatsakis should we consider extending the match ergonomics to also account for Box?


Case taken from an old reddit post from a newcomer to the language.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions