简体   繁体   English

Rust - 'while let' 语句中的双重可变借用

[英]Rust - double mutable borrow in 'while let' statement

Sorry if this is a dumb question, I'm relatively new with Rust and just can't crack this double mutable borrowing error.抱歉,如果这是一个愚蠢的问题,我对 Rust 比较陌生,只是无法破解这个双重可变借用错误。 I'm trying to create an AVL tree method that finds an appropriate position into which a new node can be inserted.我正在尝试创建一个 AVL 树方法,以找到可以插入新节点的适当 position 。 I don't understand what I need to do for the first borrow to drop.我不明白我需要做什么才能让第一次借款减少。

I'm trying to do this without RC, RefCell or Unsafe - though it's becoming increasingly unclear to me if my approach is feasible.我试图在没有 RC、RefCell 或 Unsafe 的情况下做到这一点——尽管我越来越不清楚我的方法是否可行。

Rust Playground Link Rust游乐场链接

    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
    }

I've also tried something similar to the solution described here , with no luck.我也尝试过类似于此处描述的解决方案,但没有运气。

    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
    }

This is a known limitation of the borrow checker.这是借用检查器的已知限制。 The next-gen Polonius will solve this.下一代Polonius将解决这个问题。

In the meantime, the solution (without unsafe ) is to repeat the calculation.同时,解决方案(没有unsafe )是重复计算。 In your case, this means some unwrap() s:在您的情况下,这意味着一些unwrap() s:

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

See also:也可以看看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM