generics - 如何对泛型添加约束

标签 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);
    }
}

编译错误是:

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.

我在哪里可以为 K 添加约束?

最佳答案

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

您可以在 impl 上添加约束:

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

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

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

可以引用book chapter on trait bound有关约束的更多上下文。

关于generics - 如何对泛型添加约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26359415/

相关文章:

server - 本地网络上的树莓派访问服务器

斯卡拉 : generics and variable inheritance issue

c# - 通用表达式树,每个提供的属性都有 'OR' 子句

java - 如何创建一个填充不同类型对象的 ArrayList?

rust - 如果满足条件,如何查看向量并弹出?

rust - 逐字包装辅助函数中的代码会导致借入错误

c# - 扩展方法和通用约束的问题

Java 泛型方法和作为参数的方法对象有什么区别?

functional-programming - Rust 中模式的定义是什么,什么是模式匹配?

windows - 我如何知道我的 Rust 编译器正在使用哪个 Windows 工具链?