不能将 `hsets` 借用为可变的,因为它也被借用为不可变的

cannot borrow `hsets` as mutable because it is also borrowed as immutable

想把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

如果您想更深入地了解为什么您的代码无法编译,请阅读

尝试像

一样明确 Vector 的类型
let mut arr: Vec<&str> = vec![]; // otherwise compiler is interpreting as Vec<&&str>

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=d0b4e82ab1eb12791a18cf6d33ad0ca4