Skip to content

Bad help suggestion in unused variable warning #50804

Closed
@wesleywiser

Description

@wesleywiser

I have the following code:

struct Test {
    a: usize,
    b: usize
}

fn test(x: Test) {
    let Test {
        a,
    } = x;
    
    println!("{:?}", a);
}

Since I don't need the value of b, I didn't add a binding for it in the struct destructuring. This generates an error:

error[E0027]: pattern does not mention field `b`
 --> src/main.rs:7:9
  |
7 |       let Test {
  |  _________^
8 | |         a,
9 | |     } = x;
  | |_____^ missing field `b`

error: aborting due to previous error

This makes sense to me so I'll go ahead and add b:

    let Test {
        a,
        b
    } = x;

but then this complains that b isn't used:

warning: unused variable: `b`
 --> src/main.rs:9:9
  |
9 |         b
  |         ^ help: consider using `_b` instead
  |
  = note: #[warn(unused_variables)] on by default

That also makes sense and I've used the _ prefix before to ignore values so I'll try that:

    let Test {
        a,
        _b
    } = x;

but now I get errors:

error[E0026]: struct `Test` does not have a field named `_b`
 --> src/main.rs:9:9
  |
9 |         _b
  |         ^^ struct `Test` does not have this field

error[E0027]: pattern does not mention field `b`
  --> src/main.rs:7:9
   |
7  |       let Test {
   |  _________^
8  | |         a,
9  | |         _b
10 | |     } = x;
   | |_____^ missing field `b`

error: aborting due to 2 previous errors

TLDR: We shouldn't offer the _b suggestion if it isn't valid.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions