我无法找出如何限制泛型类型。看起来像K
需要实施core::cmp::Eq and core::hash::Hash特征。我无法在文档中找到所需的语法。
use std::collections::HashMap;
struct Foo<K, V> {
map: HashMap<K, V>,
}
impl<K, V> Foo<K, V> {
fn insert_something(&mut self, k: K, v: V) {
self.map.insert(k, v);
}
}
编译器错误是:
error[E0599]: no method named `insert` found for struct `std::collections::HashMap<K, V>` in the current scope
--> src/lib.rs:9:18
|
9 | self.map.insert(k, v);
| ^^^^^^ method not found in `std::collections::HashMap<K, V>`
|
= note: the method `insert` exists but the following trait bounds were not satisfied:
`K: std::cmp::Eq`
`K: std::hash::Hash`
// Edit note, the question is old so the error message from the compiler already hint about the answer, but ignore that.
在哪里可以添加约束K
?
首先你可以导入 Hash 特征,use std::hash::Hash;
.
您可以在 impl 上添加约束:
impl<K: Eq + Hash, V> Foo<K, V>
或者,使用新的“where”语法
impl<K, V> Foo<K, V>
where
K: Eq + Hash,
您可以参考书中关于特质界限的章节有关约束的更多背景信息。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)