Skip to content

Improve error message E0608 when the type supports Index but Idx is missing trait bounds #110373

Closed
@Zannick

Description

@Zannick

I tried this code (playground):

use std::collections::HashMap;
use std::hash::Hash;

pub struct Edge<E> {
    id: E,
    src: usize,
    dst: usize,
    wt: u64
}

pub struct Graph<V, E> {
    nodes: Vec<V>,
    node_index_map: HashMap<V, usize>,
    edges: Vec<Edge<E>>,
}

pub fn build_graph<V, E>(v: V, e: E) -> Graph<V, E>
where V: Copy + Eq + Hash, E: Eq + Hash {
    let mut node_index_map = HashMap::new();
    let nodes = vec![v];
    node_index_map.insert(v, 0);
    let edges = vec![Edge { id: e, src: node_index_map[&v], dst: 0, wt: 1}];
    Graph {
        nodes,
        node_index_map,
        edges,
    }
}

impl<V, E> Graph<V, E> {
    pub fn node_index(&self, node: V) -> usize {
        self.node_index_map[&node]  // produces an error
    }
}

I expected to see this happen: rustc outputs an error saying that I need to add the Eq and std::hash::Hash traits on V.

Instead, this happened:

error[E0608]: cannot index into a value of type HashMap<V, usize>

which is jarring to see, and unhelpful, because HashMap does support Index, but only with particular trait bounds on V.

Metadata

Metadata

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsA-trait-systemArea: Trait systemC-enhancementCategory: An issue proposing an enhancement or a PR with one.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