Skip to content

mislead type ascribed to collection in a for loop diagnostic error #97163

Closed
@pnkfelix

Description

@pnkfelix

I tried this code (playground):

use std::collections::HashMap;

fn main() {
    let mut map = HashMap::new();
    map.insert(('a', 'b'), ('c', 'd'));
    
    for ((_, _), (&mut c, _)) in &mut map {
        if c == 'e' { }
    }
}

I expected to see this happen: I expect an error, but I expect the diagnostic to report types that corespond to all the expressions involved.

Instead, this happened: Part of the error diagostic claims that &mut map has type Option<(&(char, char), &mut (char, char))>

This is very confusing. In a simple case this I am certain that &mut map does not have that type, and it just ends up distracting me from the rest of the message (which does try to indicate what is wrong. But in a more complex case, where its not obvious that the compiler is misleading me, I end up wasting my time trying to figure out why map is getting a value of the wrong type here.

Herei is the specific diagnostic output I am seeing:

error[[E0308]](https://doc.rust-lang.org/nightly/error-index.html#E0308): mismatched types
 --> src/main.rs:7:19
  |
7 |     for ((_, _), (&mut c, _)) in &mut map {
  |                   ^^^^^^         -------- this expression has type `Option<(&(char, char), &mut (char, char))>`
  |                   |
  |                   expected `char`, found `&mut _`
  |                   help: you can probably remove the explicit borrow: `c`
  |
  = note:           expected type `char`
          found mutable reference `&mut _`

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsC-bugCategory: This is a bug.D-confusingDiagnostics: Confusing error or lint that should be reworked.D-incorrectDiagnostics: A diagnostic that is giving misleading or incorrect information.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions