gpt4 book ai didi

rust - 不能将 `hsets` 借为可变,因为它也被借为不可变

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

这个问题在这里已经有了答案:





How can I borrow from a HashMap to read and write at the same time?

(2 个回答)


2年前关闭。




我想将 HashSet[0] 的元素移动到 HashSet[1],但总是遇到借用错误:
我尝试使用 tmp vec 来保存元素,但问题仍然存在:

use std::collections::HashSet;

fn main() {

let mut hsets = vec![];


hsets.push(HashSet::new());
hsets[0].insert("a1");
hsets[0].insert("a2");

hsets.push(HashSet::new());
hsets[1].insert("b1");
hsets[1].insert("b2");

// tmp vec save hsets[0]: [a1, a2]
let mut arr = vec![];

for v in &hsets[0] {
arr.push(v);
}

for v2 in arr {
hsets[1].insert(v2);
}
}

结果:
error[E0502]: cannot borrow `hsets` as mutable because it is also borrowed as immutable
--> src/main.rs:18:9
|
13 | for v in &hsets[0] {
| ----- immutable borrow occurs here
...
17 | for v2 in arr {
| --- immutable borrow later used here
18 | hsets[1].insert(v2);
| ^^^^^ mutable borrow occurs here

error: aborting due to previous error

最佳答案

我假设您不想将 HashSet 移出 Vec 或取消分配它们,在这种情况下您可以这样做:

use std::collections::HashSet;

fn main() {
let mut hsets = vec![];

// first set
hsets.push(HashSet::new());
hsets[0].insert("a1");
hsets[0].insert("a2");

// second set
hsets.push(HashSet::new());
hsets[1].insert("b1");
hsets[1].insert("b2");

dbg!(&hsets);
assert_eq!(hsets[0].len(), 2);
assert_eq!(hsets[1].len(), 2);

// move elements from first set to second set
let (first, second) = hsets.split_at_mut(1);
second[0].extend(first[0].drain());

dbg!(&hsets);
assert_eq!(hsets[0].len(), 0);
assert_eq!(hsets[1].len(), 4);
}

playground

如果您想更深入地了解为什么您的代码无法编译,请阅读 How to get mutable references to two array elements at the same time? .

关于rust - 不能将 `hsets` 借为可变,因为它也被借为不可变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61635885/

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