作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我需要比较两个 serde_json::Value
小号:
enum Value {
Null,
Bool(bool),
Number(Number),
String(String),
Array(Vec<Value>),
Object(Map<String, Value>),
}
比较将返回另一个枚举:
enum Diff {
Equal,
Different,
NotFound,
}
我开始编写结构如下的代码:
fn compare(val1: &Value, val2: &Value) {
let cmp = match val1 {
Value::Null => {
if let Value::Null = val2 {
Diff::Equal
} else {
Diff::NotFound
}
}
Value::Bool(b1) => {
if let Value::Bool(b2) = val2 {
if b1 == b2 {
Diff::Equal
} else {
Diff::Different
}
} else {
Diff::NotFound
}
}
Value::Number(ref n1) => {
if let Value::Number(ref n2) = val2 {
if n1 == n2 {
Diff::Equal
} else {
Diff::Different
}
} else {
Diff::NotFound
}
}
Value::String(ref s1) => {
if let Value::String(ref s2) = val2 {
if s1 == s2 {
Diff::Equal
} else {
Diff::Different
}
} else {
Diff::NotFound
}
}
_ => {
// etc...
Diff::NotFound
}
};
}
我想避免很多代码重复。
最佳答案
您可以同时匹配 2 个值:
let cmp = match (val1, val2) {
(Value::Null, Value::Null) => Diff::Equal,
_ => {
// etc...
Diff::NotFound
}
};
您还可以实现一个转换函数或特征并使用它:
impl Diff {
fn new<T: PartialEq>(lhs: T, rhs: T) -> Diff {
if lhs == rhs { Diff::Equal } else { Diff::Different }
}
}
fn compare(val1: &Value, val2: &Value) {
let cmp = match (val1, val2) {
(Value::Null, Value::Null) => Diff::Equal,
(Value::Bool(b1), Value::Bool(b2)) => Diff::new(b1, b2),
_ => Diff::NotFound,
};
}
关于enums - 比较两个枚举的变体及其值时如何避免代码重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54606664/
我是一名优秀的程序员,十分优秀!