我很难弄清楚如何限制泛型类型。看起来 K
需要实现 core::cmp::Eq
和 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
添加约束?
最佳答案
首先你可以导入哈希特征,use std::hash::Hash;
.
您可以在 impl 上添加约束:
impl<K: Eq + Hash, V> Foo<K, V>
或者,使用新的“where”语法
impl<K, V> Foo<K, V>
where
K: Eq + Hash,
可以引用book chapter on trait bound有关约束的更多上下文。
关于generics - 如何对泛型添加约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26359415/