I have a generic struct in Rust and want the parameter K to have some trait bounds like so:
pub struct IndexStore<K, V>
where
K: std::cmp::Eq + Hash + Debug,
{
m: HashMap<K, V>,
name: Option<String>,
}
But now, whenever I write an impl block I find myself needing to write the trait bound out again. If not I get errors like "the trait bound K: std::cmp::Eq
is not satisfied". Here are some examples of my impl blocks:
impl<K, V> Deref for IndexStore<K, V>
where
K: std::cmp::Eq + Hash + Debug,
{
type Target = HashMap<K, V>;
fn deref(&self) -> &Self::Target {
&self.m
}
}
impl<K, V> DerefMut for IndexStore<K, V>
where
K: std::cmp::Eq + Hash + Debug,
{
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.m
}
}
impl<K, V> FromIterator<(K, V)> for IndexStore<K, V>
where
K: std::cmp::Eq + Hash + Debug,
{
fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
IndexStore {
m: iter.into_iter().collect(),
name: None,
}
}
}
How can I only specify the trait bound once in the struct definition without repeating it in every impl block?