I'm having trouble finding out how I constrain the generic types. It seem like K
need to implement the core::cmp::Eq
and core::hash::Hash
traits. I've been unable to find the required syntax in the docs.
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);
}
}
The compiler errors are:
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.
Where can I add constraints on K
?
First you can import the Hash trait, use std::hash::Hash;
.
You can add the constraints on the impl:
impl<K: Eq + Hash, V> Foo<K, V>
or, with the new "where" syntax
impl<K, V> Foo<K, V>
where
K: Eq + Hash,
You can refer to book chapter on trait bound for some more context on constraints.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With