- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
考虑下面的最小示例,它展示了我在一些真实代码中遇到的情况:
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
我理解上面的错误信息,我想知道解决这个问题的惯用方法。请注意:
出于可读性/可测试性的原因,我希望 fn0
和 fn1
是单独的函数。 (即它们本身就有意义。)
我想在 .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/
我对 Clojure 和函数式编程有了大约一周的了解——我的所有背景都是 OOP。我想利用 Clojure 备受争议的易读性和固有逻辑,但现在我不知道我是否成功地做到了这一点,只是没有完全理解它,或者
场景: val col: IndexedSeq[Array[Char]] = for (i = 0 && arr(last.y)(west) == '.') { arr(last.y)(w
我正面临 AngularJS、服务和范围的“问题”。 这不是一个真正的问题(我找到了几种使其工作的方法),但我想知道我是否在做正确的事情,或者我正在做的事情是否会导致将来出现问题 我有一个保存一些全局
进行以下数据结构转换的“Rubyist”方法是什么: 我有 incoming = [ {:date => 20090501, :width => 2}, {:
如何在 go 中编写返回集合最小值的函数?我不只是在寻找解决方案(我知道我可以在遍历第一个元素时只初始化最小值,然后设置一个我初始化最小值的 bool 变量),而是一个惯用的解决方案。由于 go 没有
好的,我知道我应该对我的特定应用程序进行基准测试,等等,但是: -Xmx 的默认 JVM 设置、默认垃圾收集器等,对于大多数典型的 Java 程序来说是合理的默认设置,并且可能不适合惯用的 Scala
既然 shared_ptr 在 tr1 中,你认为 std::auto_ptr 的使用会发生什么?它们都有不同的用例,但 auto_ptr 的所有用例也都可以用 shared_ptr 解决。你会放弃
这个问题在这里已经有了答案: What are the differences between type() and isinstance()? (8 个回答) 关闭 9 年前。 我需要知道 Pyth
在指定和创建数字函数时,是否有关于何时返回 null 以及何时返回 NaN 的任何 C# 惯用准则,当两者似乎都是有效输出时。 导致这个问题的具体例子是我正在为 Enumerable 集合创建一个百分
这个问题在这里已经有了答案: Retrieving the top 100 numbers from one hundred million of numbers [duplicate] (12 个
我可以通过反射检索方法,以某种方式将其与目标对象结合起来,并将其作为看起来像 Scala 中的函数的东西返回(即您可以使用括号调用它)吗?参数列表是可变的。它不一定是“一流”函数(我已经更新了问题),
我是一名优秀的程序员,十分优秀!