Skip to content

Compiler error wrongly suggests to borrow #70021

@akiross

Description

@akiross

We noticed that if a HashMap<&str, T> is instanced and a get is performed using String as a key, the rust compiler suggests to use a reference &String instead, but that solution won't compile.

For example, given this code

use std::collections::HashMap;

fn main() {
    let mut m: HashMap<&str, u32> = HashMap::new();
    let s: String = "hello".to_owned();
    m.get(s);
}

The compiler will print this error

6 |     m.get(s);
  |           ^
  |           |
  |           expected reference, found struct `std::string::String`
  |           help: consider borrowing here: `&s`
  |

and if that change is applied the error becomes

  |
6 |     m.get(&s);
  |       ^^^ the trait `std::borrow::Borrow<std::string::String>` is not implemented for `&str`

This is happening with rustc 1.42.0 on the playground.

Edit: sorry I submitted the issue by mistake while incomplete :P

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`C-bugCategory: This is a bug.D-invalid-suggestionDiagnostics: A structured suggestion resulting in incorrect code.T-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