Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add constraints on generics

Tags:

generics

rust

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?

like image 759
fadedbee Avatar asked Oct 14 '14 11:10

fadedbee


Video Answer


1 Answers

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.

like image 62
Paolo Falabella Avatar answered Oct 01 '22 20:10

Paolo Falabella