繁体   English   中英

Rust - 不能作为可变借用

[英]Rust - cannot borrow as mutable

我在尝试运行此代码时遇到错误:

use serde_json::{json, Map, Value};

fn get_json() -> Map<String, Value>{
    let r = json!({
        "x": "y"
    });
    let r = r.as_object().unwrap();
    return r.clone();
}
fn main() {
    let mut a = get_json();
    
    let mut d: Map<String, Value> = Map::new();
    let x = a["x"].as_str().unwrap();
    a.insert("g".to_string(), Value::String("x".to_string()));
    d.insert(x.to_string(), Value::Object(a));
}

错误:

cannot borrow `a` as mutable because it is also borrowed as immutable
mutable borrow occurs hererustcE0502
main.rs(14, 13): immutable borrow occurs here
main.rs(16, 14): immutable borrow later used here

我什至不想借 a,我只是想插入一些东西。

怎么样:

use serde_json::{json, Map, Value};

fn get_json() -> Map<String, Value> {
    let r = json!({
        "x": "y"
    });
    r.as_object().unwrap().clone()
}

fn main() {
    let mut a = get_json();
    a.insert("g".to_string(), Value::String("x".to_string()));
    let d = Map::<String, Value>::from_iter(vec![(a["x"].to_string(), Value::Object(a))]);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM