当我将 HashMap 放入结构中时,为什么编译器会说 Hash 未实现?

问题描述 投票:0回答:1

我试图在我的结构中以非常基本的方式使用 HashMap,但我对这个错误感到困惑......我错过了什么?

error[E0277]: the trait bound `HashMap<&str, &T>: Hash` is not satisfied
   --> src/file.rs:290:5
    |
282 | #[derive(PartialEq, Eq, Hash)]
    |                         ---- in this derive macro expansion
...
290 |     enums: &'a HashMap<&'a str, &'a T>,
    |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Hash` is not implemented for `HashMap<&str, &T>`
    |
    = note: required for `&HashMap<&str, &T>` to implement `Hash`
    = note: this error originates in the derive macro `Hash` (in Nightly builds, run with -Z macro-backtrace for more info)

Rust 游乐场示例:link

&str
应该实现所有特征,是/否?

这是我用来展示此问题的示例代码:

    use std::collections::HashMap;
    use std::hash::Hash;

    trait Pt<'a> {
        fn is_int(&self) -> bool;
    }

    #[derive(PartialEq, Eq, Hash)]
    struct Enumeration<'a, T: Pt<'a>>
    where
        T: ?Sized + Eq + Hash,
    {
        pt: &'a T,
        max_length: u8,
        enum_name: &'a str,
        enums: &'a HashMap<&'a str, &'a T>,
        reverse_enums: HashMap<&'a T, &'a str>,
    }
rust hashmap traits implements
1个回答
1
投票

此错误与

HashMap
本身 未实现
Hash
特性有关。无论键和值的类型如何,事实并非如此。而且,因为当您
#[derive(Hash)]
对于一个结构时,它要求它的所有元素也实现
Hash
,因此您不能对外部结构执行此操作。

您可以放弃实施

Hash
来实现
Enumeration
,或者必须手动执行。

© www.soinside.com 2019 - 2024. All rights reserved.