Cannot obtain a mutable reference when iterating a recursive structure: cannot borrow as mutable more than once at a time

前端 未结 4 1806
盖世英雄少女心
盖世英雄少女心 2020-11-22 07:05

I\'m trying to navigate a recursive data structure iteratively in order to insert elements at a certain position. To my limited understanding, this means taking a mutable re

4条回答
  •  野性不改
    2020-11-22 07:46

    The original code works as-is once non-lexical lifetimes are enabled:

    type Link = Option>;
    
    struct Node {
        next: Link,
    }
    
    struct Recursive {
        root: Link,
    }
    
    impl Recursive {
        fn back(&mut self) -> &mut Link {
            let mut anchor = &mut self.root;
            while let Some(node) = anchor {
                anchor = &mut node.next;
            }
            anchor
        }
    }
    

    Non-lexical lifetimes increases the precision of the compiler's borrow checker, allowing it to see that the mutable borrow of anchor is no longer used. We can also simplify the keywords in the if let due to recent language changes.

提交回复
热议问题