如何为自己的结构实现Eq和Hash以将其用作HashMap键? [英] How to implement Eq and Hash for my own structs to use them as a HashMap key?

查看:82
本文介绍了如何为自己的结构实现Eq和Hash以将其用作HashMap键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个结构,AB,我想使用HashMap<A, B>.我有一段这样的代码:

I have two structs, A and B, and I want to use a HashMap<A, B>. I have a piece of code like this:

use std::collections::HashMap;

pub struct A {
    x: i32,
    y: i32,
    title: String,
}

pub struct B {
    a: u32,
    b: u32,
}

fn main() {
    let map = HashMap::new();
    map.insert(
        A {
            x: 10,
            y: 20,
            title: "test".to_string(),
        },
        B { a: 1, b: 2 },
    );
}

但是编译器给了我这些错误:

But the compiler gives me these errors:

error[E0277]: the trait bound `A: std::cmp::Eq` is not satisfied
  --> src/main.rs:16:9
   |
16 |     map.insert(
   |         ^^^^^^ the trait `std::cmp::Eq` is not implemented for `A`

error[E0277]: the trait bound `A: std::hash::Hash` is not satisfied
  --> src/main.rs:16:9
   |
16 |     map.insert(
   |         ^^^^^^ the trait `std::hash::Hash` is not implemented for `A`

我知道我必须实现这些特征,但是经过数小时的网上搜索,我仍然没有发现有关实现这些特征的任何信息.

I know that I must implement these traits, but after hours of searching the web, I have found nothing about implementing them.

我的实际代码更加复杂,并且我的结构包含其他结构(我已经编辑了代码).

My actual code is more complicated, and my structs contain other structs (I've edited the code).

我已经实现了Hash特质:

impl std::hash::Hash for A {
    fn hash<H>(&self, state: &mut H)
    where
        H: std::hash::Hasher,
    {
        state.write_i32(self.x);
        state.finish();
    }
}

我还为PartialEq做了一个实现:

impl PartialEq for A {
    fn eq(&self, other: &A) -> bool {
        self.x == other.x
    }
}

但是编译器仍在抱怨,这次是关于Eq:

But the compiler continues to complain, this time about Eq:

error[E0277]: the trait bound `A: std::cmp::Eq` is not satisfied
  --> src/main.rs:16:9
   |
16 |     map.insert(
   |         ^^^^^^ the trait `std::cmp::Eq` is not implemented for `A`

如何实现Eq?为什么文档中没有实现?

How can I implement Eq? Why is there no implementation in the docs?

推荐答案

Eq是我们所说的标记特征:它没有单独的方法,它只是程序员表达结构验证的一种方式某种财产.您可以这样实现:

Eq is what we call a marker trait: it has no method on its own, it is just a way for the programmer to express that the struct verifies a certain property. You can implement it like this:

impl Eq for Application {}

或者,在Application声明的顶部使用#[derive(Eq)]

Or alternatively, use #[derive(Eq)] on top of the Application declaration

Eq是受PartialEq约束的特征.这意味着您只能在也实现PartialEq的结构上实现它(这里就是这种情况).通过实现Eq,您可以保证PartialEq的实现是自反的(有关含义,请参阅文档).

Eq is a trait bound by PartialEq. This means that you can implement it only on structs that also implement PartialEq (which is the case here). By implementing Eq, you make the promise that your implementation of PartialEq is reflexive (see the docs for what it means).

这篇关于如何为自己的结构实现Eq和Hash以将其用作HashMap键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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