'Rust - cannot borrow as mutable

I'm getting an error trying to run this code:

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));
}

Error:

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

I'm not even trying to borrow a, I'm only trying to insert something to it.



Solution 1:[1]

How about:

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))]);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hkBst