我想将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
答案 0 :(得分:0)
我假设您不想将HashSets移出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);
}
如果您想更深入地了解为什么不能按原样编译代码,请阅读How to get mutable references to two array elements at the same time?。
答案 1 :(得分:0)
尝试明确说明Vector的类型,例如
let mut arr: Vec<&str> = vec![]; // otherwise compiler is interpreting as Vec<&&str>