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

前端 未结 4 1803
盖世英雄少女心
盖世英雄少女心 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

    You can use recursion to satisfy the borrow checker. This has the disadvantage of creating a stack frame for every item in your list. If your list is long, this will definitely run into a stack overflow. LLVM will optimize the Node::back method into a loop (see the LLVM IR generated on the playground)

    impl Node {
        fn back(&mut self) -> &mut Link {
            match self.next {
                Some(ref mut node) => node.back(),
                None => &mut self.next,
            }
        }
    }
    
    impl Recursive {
        fn back(&mut self) -> Option<&mut Link> {
            self.root.as_mut().map(|node| node.back())
        }
    }
    

提交回复
热议问题