我有一个自定义Node
类型和一个BTreeSet
这些节点。我想从BTreeSet
中删除一个节点,理想情况下不复制数据。我想在集合中搜索该节点,返回一个引用,并使用返回的引用在集合上调用remove
。我想通过不变地借出数据结构来找到一个节点,然后在找到它之后,通过不变地借出数据结构来删除它:
use std::collections::BTreeSet;
#[derive(Clone, Debug, Ord, PartialOrd, PartialEq, Eq)]
pub struct Node {
pub order: i32,
}
pub fn find_node<'a>(set: &'a BTreeSet<Node>, order: &i32) -> Option<&'a Node> {
for el in set.iter() {
if *order == el.order {
return Some(el);
}
}
None
}
fn main() {
let mut set: BTreeSet<Node> = BTreeSet::new();
let n1 = Node { order: 1 };
let n2 = Node { order: 2 };
let n3 = Node { order: 3 };
set.insert(n1);
set.insert(n2);
set.insert(n3);
let to_remove: Option<&Node> = match find_node(&set, &2) {
Some(to_remove) => Some(to_remove),
None => None,
};
match to_remove {
Some(to_remove) => {
set.remove(&to_remove);
}
None => {}
}
println!("Hello, world!");
}
我得到一个错误:
error[E0502]: cannot borrow `set` as mutable because it is also borrowed as immutable
--> src/main.rs:32:13
|
26 | let to_remove: Option<&Node> = match find_node(&set, &2) {
| --- immutable borrow occurs here
...
32 | set.remove(&to_remove);
| ^^^ mutable borrow occurs here
...
38 | }
| - immutable borrow ends here
最好的方法是什么?