You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust中while let语句的双重可变借用错误解决咨询

Rust双重可变借用错误:AVL树插入位置查找问题

刚接触Rust,在实现AVL树中查找新节点插入位置的方法时,一直无法解决双重可变借用错误。尝试不使用RC、RefCell或Unsafe来实现,但不确定这种方法是否可行。

第一种实现代码

pub fn find_pos(&mut self, key: &K) -> &mut Link<K, V>{
    let mut current = &mut self.root;
    while let Some(node) = current.as_mut() {  // <- first mutable borrow
        match node.key.cmp(&key) {
            Ordering::Equal => break,
            Ordering::Greater => {
                current = &mut node.right;
            },
            Ordering::Less => {
                current = &mut node.left;
            },
        }
    };
    current  // <- second mutable borrow
}

第二种尝试的代码(参考Stack Overflow方案但无效)

pub fn find_pos(&mut self, key: &K) -> &mut Link<K, V> {
    let mut current = &mut self.root;
    loop {
        let tmp = current;
        if let Some(ref mut node) = *tmp {
           match node.key.cmp(&key) {
               Ordering::Equal => {
                   current = tmp;
                   break
               },
               Ordering::Greater => {current = &mut node.right},
               Ordering::Less => {current = &mut node.left},
           }
        } else {
            current = tmp;
            break
        }
    }
    current
}

内容的提问来源于stack exchange,提问作者Skelectric

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 10:55:16