如何在泛型上添加约束 [英] How to add constraints on generics

查看:64
本文介绍了如何在泛型上添加约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找如何约束泛型类型时遇到了麻烦.似乎K需要实现 core::cmp::Eq core::hash::Hash 特征.我一直无法在文档中找到所需的语法.

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

编译器错误为:

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上添加约束?

Where can I add constraints on K?

推荐答案

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

First you can import the Hash trait, use std::hash::Hash;.

您可以在impl上添加约束:

You can add the constraints on the impl:

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

,或者使用新的"where"语法

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.

这篇关于如何在泛型上添加约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆