提问人:abdoe 提问时间:10/15/2017 最后编辑:Shepmasterabdoe 更新时间:10/15/2017 访问量:160
分配可变变量后如何处理?
How to deal with a mutable variable once it is assigned?
问:
从其他问题中,我弄清楚了如何构建复杂的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
答: 暂无答案
评论
json!
let is_null = curr_obj.is_null();