[英]Implementing a trait on HashMap that uses methods with bounds
我要在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语句添加相同的界限。 如何修复此代码?
错误:找不到类型为
contains_key
方法
如你的文档中看到contains_key
,所述impl
其中块contains_key
定义,具有边界where K: Eq + Hash, S: HashState
。 在您的where子句中添加K的界限也将解决其他no method
错误,并且cannot index a value of type
std :: collections :: hash :: map :: HashMap`错误的值。
之后,你得到
错误:非标量转换:
usize
V
对应于此行:
let id = self.len() as V;
您要在此处执行的操作是将usize
转换为实例usize
V
任何类型。 一般来说,这是行不通的,因为V
可能实际上与usize
不兼容(例如Vec
或任何其他结构)。 由于您真正想要的是从某个键到id的HashMap
,因此您可以简单地删除所有V
泛型并直接设置HashMap
的Value参数:
trait IdAssigner<K> {
fn assign_id(mut self, key: K) -> (usize, bool);
}
impl<K> IdAssigner<K> for HashMap<K, usize>
where K: Eq + Hash,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.