Skip to content

Misleading cannot infer type for type parameter #93198

Closed
@Patryk27

Description

@Patryk27

Given the following code:

use std::collections::HashMap;

trait Store<K, V> {
    fn get_raw(&self, key: &K) -> Option<()>;
}

struct InMemoryStore;

impl<K> Store<String, HashMap<K, String>> for InMemoryStore {
    fn get_raw(&self, key: &String) -> Option<()> {
        None
    }
}

fn main() {
    InMemoryStore.get_raw(&String::default());
}

(playground link)

... the current output is:

error[E0282]: type annotations needed
  --> src/main.rs:16:19
   |
16 |     InMemoryStore.get_raw(&String::default());
   |                   ^^^^^^^ cannot infer type for type parameter `K`

This error message is a bit misleading in that it refers not to K from trait Store<K, V>, but K from the impl<K> Store<...> (the compiler is not sure which kind of HashMap<K, String> user wants).

Maybe we could print something like this?

error[E0282]: type annotations needed
  --> src/main.rs:16:19
   |
16 |     InMemoryStore.get_raw(&String::default());
   |                   ^^^^^^^ cannot infer type for type parameter `K`...
   |
  ::: src/main.rs:9
   |
 9 | impl<K> Store<String, HashMap<K, String>> for InMemoryStore {
          ^ ... from this impl

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsT-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