How to add constraints on generics

[亡魂溺海] 提交于 2020-12-04 00:38:17

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/26359415/how-to-add-constraints-on-generics

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!