我想在HashMaps上实现以下特征:
trait IdAssigner<K, V> {
// If key has already been seen, returns (id_for_key, false). Otherwise
// assigns a new id_for_key (starting with 0 and increasing) and returns
// (id_for_key, true).
fn assign_id(mut self, key: K) -> (V, bool);
}
impl<K, V> IdAssigner<K, V> for HashMap<K, V> where V: Add<V> {
fn assign_id(mut self, key: K) -> (V, bool) {
if self.contains_key(&key) {
(self[&key], false)
} else {
let id = self.len() as V;
self[&key] = id;
(id, true)
}
}
}
编译器给出了我想在HashMap的实现中调用的方法的各种错误 . 我怀疑我需要在我的impl语句中添加相同的边界,这些边界存在于这些方法中 . 我该如何修复此代码?
1 回答
正如您在contains_key的文档中看到的那样,定义了
contains_key
的impl
块具有边界where K: Eq + Hash, S: HashState
. 将K的绑定添加到where子句也将修复其他no method
错误和cannot index a value of type
std :: collections :: hash :: map :: HashMap`错误 .之后你会得到
对应于这一行:
你在这里要做的是将
usize
转换为V
实例化的任何类型 . 这通常不起作用,因为V
实际上可能是与usize
(例如Vec
或任何其他结构)不兼容的东西 . 因为你真正想要的是从某个键到id的HashMap
,你可以简单地删除所有V
泛型并直接设置HashMap
的Value参数: