I need a function similar to assocPath, I want to confirm whether a certain child node exists, if it exists, obtain its mutable reference, if it does not exist, create and obtain that.
I encountered some difficulties, my parent node is a mutable reference, and the child node is also a mutable reference, so the reference of the parent node should be released, but the compiler some how tells me that "cannot assign twice to immutable variable", this confuses me.
The following is my attemption, how can I solve this?
use std::collections::HashMap;
pub enum JsonValue {
Null,
Bool(bool),
Number(f32),
String(String),
Array(Vec<JsonValue>),
Object(HashMap<String, JsonValue>),
}
impl JsonValue {
fn new() -> JsonValue { JsonValue::Object(HashMap::new()) }
fn check_key_path(mut self, path: &str) -> &JsonValue {
let ref mut node = self;
for k in path.split(".") {
match node {
JsonValue::Object(dict) => {
node = match dict.get(k) {
Some(ref mut s) => s,
None => &mut dict.insert(k.to_string(), JsonValue::new()).unwrap()
}
}
_ => panic!("NotObject")
}
}
node
}
}
fn main() {
let mut v = JsonValue::new();
v.check_key_path("some.node.path");
}