I have a custom Node
type and a BTreeSet
of these nodes. I would like to remove a node from the BTreeSet
, ideally without copying the data. I would like to search the set for the node, return a reference, and call remove
on the set with the returned reference. I want to find a node by immutably lending a data structure and then after finding it, remove it by lending the data structure immutably:
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!");
}
I get an error:
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
What's the best way to do this?