Rust deep clone and recursive merge for nested maps
Rust
use std::collections::BTreeMap;
#[derive(Clone, Debug, PartialEq)]
enum Value {
Scalar(String),
Obj(BTreeMap<String, Value>),
}
fn merge(base: &Value, patch: &Value) -> Value {
match (base, patch) {
(Value::Obj(a), Value::Obj(b)) => {
let mut out = a.clone();
for (k, v) in b {
let next = a.get(k).map_or_else(|| v.clone(), |old| merge(old, v));
out.insert(k.clone(), next);
}
Value::Obj(out)
}
(_, other) => other.clone(),
}
}