0

我有一个自定义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

最好的方法是什么?

4

0 回答 0