ref*_*los 1 rust borrow-checker
我想将一个对象放入 serde_json::Map 中,其中键将是该对象内部的值。
use serde_json::{json, Map, Value};
fn main() {
let a = json!({
"x": "y"
});
let mut d: Map<String, Value> = Map::new();
d[&a["x"].to_string()] = a;
}
Run Code Online (Sandbox Code Playgroud)
错误:
borrow of moved value: `a`
value borrowed here after moverustcE0382
main.rs(9, 30): value moved here
main.rs(4, 9): move occurs because `a` has type `Value`, which does not implement the `Copy` trait
Run Code Online (Sandbox Code Playgroud)
即使您解决了这个生命周期问题, 的IndexMut实现也Map不能用于将新元素插入到映射中。如果给定的密钥不存在,它会出现恐慌。
使用insert()该方法,可以解决这两个问题:
d.insert(a["x"].to_string(), a);
Run Code Online (Sandbox Code Playgroud)