Skip to content

Improve compiler error for missing Clone trait bound #76643

Closed
@mpizenberg

Description

@mpizenberg

I just faced a compiler error when trying to clone a hashmap parameterized by a non-clone type. The error was a bit cryptic, about not expecting a reference, until I realized I've forgot to add the T: Clone trait bound. Here is a minimal function reproducing my issue:

fn clone_map<T>(map1: &HashMap<String, T>) -> HashMap<String, T> {
    map1.clone()
}

And here is the error I got:

7 | fn clone_map<T>(map1: &HashMap<String, T>) -> HashMap<String, T> {
  |                                               ------------------ expected `std::collections::HashMap<std::string::String, T>` because of return type
8 |     map1.clone()
  |     ^^^^^^^^^^^^ expected struct `std::collections::HashMap`, found reference
  |
  = note: expected struct `std::collections::HashMap<std::string::String, T>`
          found reference `&std::collections::HashMap<std::string::String, T>`

The code is available in the playground here. I was wondering if the compiler could deduce that the mistake here could be a missing trait bound and give that hint to the developer.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsD-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions