gpt4 book ai didi

rust - 闭包中的可变与不可变借用?

转载 作者:行者123 更新时间:2023-12-03 11:25:28 28 4
gpt4 key购买 nike

我不知道如何使以下内容起作用。我想我需要闭包借用 &mut Vec ,但我不知道如何表达。这是从一个更大的函数中提取出来的,但显示了相同的错误。

fn main() {
let mut v = vec![0; 10];

let next = |i| (i + 1) % v.len();

v[next(1usize)] = 1;

v.push(13);

v[next(2usize)] = 1;
}
错误:
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
--> a.rs:9:5
|
5 | let next = |i| {
| --- immutable borrow occurs here
6 | (i + 1) % v.len()
| - first borrow occurs due to use of `v` in closure
...
9 | v[next(1usize)] = 1;
| ^ ---- immutable borrow later used here
| |
| mutable borrow occurs here

error: aborting due to previous error

最佳答案

如果你真的想用闭包来做,你将不得不通过参数传递向量:

let next = |v: &Vec<_>, i| (i + 1) % v.len();
这使得闭包每次调用借用,而不是为范围捕获。但是,您仍然需要分开借用:
let j = next(&v, 1usize);
v[j] = 1;
为了让你的生活更轻松,你可以把所有东西都放在闭包里:
let next = |v: &mut Vec<_>, i, x| {
let j = (i + 1) % v.len();
v[j] = x;
};
这使您可以简单地执行以下操作:
next(&mut v, 1usize, 1);
next(&mut v, 2usize, 2);
// etc.
这种模式对于您编写闭包只是为了避免本地代码重复的情况很有用(我怀疑这就是您询问注释的原因)。

关于rust - 闭包中的可变与不可变借用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65646778/

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