我正在用Rust写一个解释器,遇到了这个我不知道如何解决的错误。它是由包含HashMap
的枚举变体之一引起的:
use std::collections::HashMap;
// stubbed type
#[derive(Debug, PartialEq, Clone, Eq, PartialOrd, Hash)]
struct Expression;
#[derive(Debug, PartialEq, Clone, Eq, PartialOrd, Hash)]
enum Literal {
Integer(i64),
Bool(bool),
String(String),
Array(Vec<Expression>),
Hash(HashMap<Expression, Expression>),
}
error[E0277]: can't compare `HashMap<Expression, Expression>` with `HashMap<Expression, Expression>`
--> src/lib.rs:13:10
|
7 | #[derive(Debug, PartialEq, Clone, Eq, PartialOrd, Hash)]
| ---------- in this derive macro expansion
...
13 | Hash(HashMap<Expression, Expression>),
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ no implementation for `HashMap<Expression, Expression> < HashMap<Expression, Expression>` and `HashMap<Expression, Expression> > HashMap<Expression, Expression>`
|
= help: the trait `PartialOrd` is not implemented for `HashMap<Expression, Expression>`
error[E0277]: the trait bound `HashMap<Expression, Expression>: Hash` is not satisfied
--> src/lib.rs:13:10
|
7 | #[derive(Debug, PartialEq, Clone, Eq, PartialOrd, Hash)]
| ---- in this derive macro expansion
...
13 | Hash(HashMap<Expression, Expression>),
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Hash` is not implemented for `HashMap<Expression, Expression>`
错误说PartialOrd
不是为HashMap<Expression, Expression>
实现的,但据我所知,HashMap
是无序的,所以我为什么需要它?
我需要做什么来修复它?
上面是#[derive(..., PartialOrd, ...)]
。这意味着所有枚举变体都应该实现PartialOrd
。这就是为什么编译器希望HashMap<Expression, Expression>
实现PartialOrd
。
将HashMap
从变体中移除,将PartialOrd
从#[derive(...)]
中移除,或者使用像BTreeMap
一样实现PartialOrd
的映射类型
Hash
性状也是如此。