小编bil*_*rer的帖子

获取 HashMap 条目,如果没有则添加它

我想做这样的事情:

fn some_fn() {
    let mut my_map = HashMap::from([
        (1, "1.0".to_string()),
        (2, "2.0".to_string()),
    ]);

    let key = 3;

    let res = match my_map.get(&key) {
        Some(child) => child,
        None => {
            let value = "3.0".to_string();
            my_map.insert(key, value);
            &value // HERE IT FAILS
        }
    };

    println!("{}", res);
}
Run Code Online (Sandbox Code Playgroud)

但编译时出现错误:

error[E0597]: `value` does not live long enough
  --> src/lib.rs:16:13
   |
16 |             &value // HERE IT FAILS
   |             ^^^^^^
   |             |
   |             borrowed value does not live long enough
   |             borrow later used …
Run Code Online (Sandbox Code Playgroud)

hashmap rust borrow-checker

1
推荐指数
1
解决办法
1929
查看次数

标签 统计

borrow-checker ×1

hashmap ×1

rust ×1