如何解决在枚举上检查PartialEq而不检查变体的附加数据
例如,假设这是一个Json解析器,并代表包含我的可能数据的每个变体,都使用枚举。
#[derive(Copy,Clone,PartialEq)]
enum JsonObject {
Invalid,Null,Bool(boo),/// etc
}
现在在代码的某些部分中,我比较了两个JsonObjects
let type1 = JsonObject::Bool(true);
let type2 = JsonObject::Bool(false);
if type1 == type2 {
// do stufff
}
问题是type1 != type2
是因为JsonObject::Bool(true) != JsonObject::Bool(false)
,我想要的是枚举不比较变体的内部数据,而只是比较变体本身。
JsonObject::Bool(_) == JsonObject::Bool(_)
解决方法
默认情况下,派生的PartialEq
将比较所有内容,包括您注意到的包装值。
对于自定义行为,必须手动实现。
幸运的是,Rust 1.21.0
及更高版本对此具有std::mem::discriminant
的功能:
use std::{
cmp::PartialEq,mem::discriminant,};
impl PartialEq for JsonObject {
fn eq(&self,other: &Self) -> bool {
discriminant(self) == discriminant(other)
}
}
较旧的答案
use std::cmp::PartialEq;
impl PartialEq for JsonObject {
fn eq(&self,other: &Self) -> bool {
use JsonObject::*;
match (self,other) {
(Invalid,Invalid) => true,(Null,Null) => true,(Bool(_),Bool(_)) => true,_ => false
}
}
}
,
有了Indriya条板箱,您可以那样做
extern crate strum;
#[macro_use]
extern crate strum_macros;
#[derive(Copy,Clone,EnumDiscriminants)]
enum JsonObject {
Invalid,Null,Bool(bool),// etc
}
impl std::cmp::PartialEq for JsonObject {
fn eq(&self,other: &Self) -> bool {
JsonObjectDiscriminants::from(self) == other.into()
}
}
编辑:感谢strum
,在没有其他依赖项的情况下完美运行
#[derive(Copy,Clone)]
enum JsonObject {
Invalid,other: &Self) -> bool {
use std::mem::discriminant;
discriminant(self) == discriminant(other)
}
}
fn main() {
assert!(JsonObject::Bool(true) == JsonObject::Bool(false));
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。