我有以下代码:
use std::collections::{HashMap, HashSet};
fn populate_connections(
start: i32,
num: i32,
conns: &mut HashMap<i32, HashSet<i32>>,
ancs: &mut HashSet<i32>,
) {
let mut orig_conns = conns.get_mut(&start).unwrap();
let pipes = conns.get(&num).unwrap();
for pipe in pipes.iter() {
if !ancs.contains(pipe) && !orig_conns.contains(pipe) {
ancs.insert(*pipe);
orig_conns.insert(*pipe);
populate_connections(start, num, conns, ancs);
}
}
}
fn main() {}
逻辑并不是很重要,我正在尝试创建一个函数,它将自身传递并在管道上行走。
我的问题是,这段代码无法编译:
error[E0502]: cannot borrow `*conns` as immutable because it is also borrowed as mutable
--> src/main.rs:10:17
|
9 | let mut orig_conns = conns.get_mut(&start).unwrap();
| ----- mutable borrow occurs here
10 | let pipes = conns.get(&num).unwrap();
| ^^^^^ immutable borrow occurs here
...
19 | }
| - mutable borrow ends here
error[E0499]: cannot borrow `*conns` as mutable more than once at a time
--> src/main.rs:16:46
|
9 | let mut orig_conns = conns.get_mut(&start).unwrap();
| ----- first mutable borrow occurs here
...
16 | populate_connections(start, num, conns, ancs);
| ^^^^^ second mutable borrow occurs here
...
19 | }
| - first borrow ends here
我不知道如何使它工作。一开始,我试图将两个 HashSet
存储在 HashMap
( orig_conns
和 pipes
)中。
Rust不允许我同时拥有可变和不可变变量。我有点困惑,因为这将是完全不同的对象,但我想如果&start
== &num
,那么我将有两个对同一对象的不同引用(一个可变,一个不可变)。
没关系,但我该怎么做呢?我要遍历一个 HashSet
,并读取和修改另一个 HashSet
。假设它们不会是相同的 HashSet
。
get_mut_pair()
和其他几种方法,可以让哈希表拥有多个可变引用。 - ANimator120