在 Rust 中,我希望将枚举类型视为相等,但仍能通过指针区分不同的实例。以下是一个玩具示例:
use self::Piece::*;
use std::collections::HashMap;
#[derive(Eq, PartialEq)]
enum Piece {
Rook,
Knight,
}
fn main() {
let mut positions: HashMap<&Piece, (u8, u8)> = HashMap::new();
let left_rook = Rook;
let right_rook = Rook;
positions.insert(&left_rook, (0, 0));
positions.insert(&right_rook, (0, 7));
}
然而,编译器要求我在Piece
上定义Hash
:
error[E0277]: the trait bound `Piece: std::hash::Hash` is not satisfied
--> src/main.rs:11:52
|
11 | let mut positions: HashMap<&Piece, (u8, u8)> = HashMap::new();
| ^^^^^^^^^^^^ the trait `std::hash::Hash` is not implemented for `Piece`
|
= note: required because of the requirements on the impl of `std::hash::Hash` for `&Piece`
= note: required by `<std::collections::HashMap<K, V>>::new`
error[E0599]: no method named `insert` found for type `std::collections::HashMap<&Piece, (u8, u8)>` in the current scope
--> src/main.rs:15:15
|
15 | positions.insert(&left_rook, (0, 0));
| ^^^^^^
|
= note: the method `insert` exists but the following trait bounds were not satisfied:
`&Piece : std::hash::Hash`
error[E0599]: no method named `insert` found for type `std::collections::HashMap<&Piece, (u8, u8)>` in the current scope
--> src/main.rs:16:15
|
16 | positions.insert(&right_rook, (0, 7));
| ^^^^^^
|
= note: the method `insert` exists but the following trait bounds were not satisfied:
`&Piece : std::hash::Hash`
我希望在我的枚举类型上定义相等性,以便一个 Rook
等于另一个。然而,我希望能够区分我的 positions
哈希映射中的不同 Rook
实例。
我该怎么做?我不想在 Piece
上定义 Hash
,但是指针上已经定义了哈希函数,是吗?
: HashMap<&Piece, (u8, u8)>
类型说明 - 所有内容都可以被推断出来。 - Shepmaster