gpt4 book ai didi

dictionary - 如何使用 map .or_insert_with 解决 self 借用问题?使用rust (1.11)

转载 作者:行者123 更新时间:2023-11-29 08:21:08 24 4
gpt4 key购买 nike

<分区>

这段代码

use std::collections::HashMap;

struct Foo {
local_ids: HashMap<i32, i32>,
last_id: i32,
}

impl Foo {
fn foo(&mut self, external_id: i32) {
let id = self.local_ids
.entry(external_id)
.or_insert_with(||{self.last_id += 1; self.last_id});
}
}

不起作用,因为我们不能两次借用 self

error: closure requires unique access to `self` but `self.local_ids` is already borrowed [E0500]

这是否可以在不进行第二次 key 查找的情况下修复?


这与 Rust: HashMap borrow issue when trying to implement find or insert 非常相似,但 API 发生了重大变化。

上面的 find_with_or_insert_with 答案似乎没有映射到当前的 api。

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com