从其他问题,我想出了如何构建复杂的JSON对象。要正确获取我的JSON对象,我需要检查是否已为此result_object
分配了“密钥”。
由于对象现在是&mut
,我无法将其用于其他操作,例如if
条件。
我该如何处理这样的情况?
#[macro_use]
extern crate serde_json;
fn main() {
let my_vec = ["foo", "bar", "baz", "foobar", "barfoo"];
let mut curr_obj = json!(null);
{
let mut obj_ref = &mut curr_obj;
for i in 0..my_vec.len() {
let name = my_vec[i];
if curr_obj.is_null() {
//do stuff
}
obj_ref = &mut { obj_ref }[name]; // note the curly braces
}
}
println!("{:?}", curr_obj);
}
错误:
error[E0502]: cannot borrow `curr_obj` as immutable because it is also borrowed as mutable
--> src/main.rs:12:16
|
8 | let mut obj_ref = &mut curr_obj;
| -------- mutable borrow occurs here
...
12 | if curr_obj.is_null() {
| ^^^^^^^^ immutable borrow occurs here
...
17 | }
| - mutable borrow ends here