如何在泛型上添加约束

fad*_*bee 5 generics rust

我很难找出我如何约束泛型类型。似乎K需要实现core::cmp::Eqcore::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);
    }
}
Run Code Online (Sandbox Code Playgroud)

编译器错误是:

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.
Run Code Online (Sandbox Code Playgroud)

我可以在哪里添加约束K

Pao*_*lla 8

首先,您可以导入哈希特征,use std::hash::Hash;.

您可以在 impl 上添加约束:

impl<K: Eq + Hash, V> Foo<K, V>

或者,使用新的“where”语法

impl<K, V> Foo<K, V>
where
    K: Eq + Hash,
Run Code Online (Sandbox Code Playgroud)

你可以参考关于 trait bound 的书籍章节,了解更多关于约束的上下文。