gpt4 book ai didi

rust - 解决嵌套可变借用冲突的惯用方法

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

考虑下面的最小示例,它展示了我在一些真实代码中遇到的情况:

use std::collections::HashSet;
type HS = HashSet<String>;

fn fn1(x: String, hs0: &mut HS, hs1: &mut HS) {
// ...
}

fn fn0(hs0: &mut HS, hs1: &mut HS) {
hs0.get("").map(|x| fn1(x.clone(), hs0, hs1));
}

fn main() {
let mut hs0 = HS::new();
let mut hs1 = HS::new();
fn0(&mut hs0, &mut hs1);
}

借用检查员不高兴:

error[E0500]: closure requires unique access to `hs0` but `*hs0` is already borrowed
--> <anon>:9:21
|
9 | hs0.get("").map(|x| fn1(x, hs0, hs1));
| --- ^^^ --- - borrow ends here
| | | |
| | | borrow occurs due to use of `hs0` in closure
| | closure construction occurs here
| borrow occurs here

on the Rust playground


我理解上面的错误信息,我想知道解决这个问题的惯用方法。请注意:

  • 出于可读性/可测试性的原因,我希望 fn0fn1 是单独的函数。 (即它们本身就有意义。)

  • 我想在 .map(...) 链式调用中使用相同的参数从 fn0 调用 fn1

不使用 .map 是唯一明智的选择吗?

最佳答案

粗略地说,hs0 一直被借用,直到没有对它的任何部分的引用。也就是说,当 x: &String 存在时,您不能可变地借用 hs0。这意味着我们需要做一些事情来结束 x 的生命周期,比如将其转换为 String 并将该字符串传递给下一个 map

fn fn0(hs0: &mut HS, hs1: &mut HS) {
hs0.get("").map(|x| x.clone()).map(|x| fn1(x, hs0, hs1));
}

关于rust - 解决嵌套可变借用冲突的惯用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44775806/

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