无法借用'hsets'可变,因为它也被借为不可变的

问题描述 投票:0回答: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
rust immutability borrow
2个回答
0
投票

[尝试明确说明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


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);
}

playground

[如果您想更深入地了解为什么不能按原样编译代码,请阅读How to get mutable references to two array elements at the same time?

© www.soinside.com 2019 - 2024. All rights reserved.