Closed
Description
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
.