我想将 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