How to implement an iterator of mutable references to the values in the right edges of a Binary Search Tree?

后端 未结 2 1885
孤独总比滥情好
孤独总比滥情好 2021-01-13 10:38

I implemented a simple Binary Search Tree in Rust (following CIS 198, it\'s great), and for learning I\'m doing iterators that just run through the right edges.

I c

相关标签:
2条回答
  • 2021-01-13 11:13

    I think you cannot split self into 2 mutable objects (one for the Item, one for self itself) without using some unsafe code.

    0 讨论(0)
  • 2021-01-13 11:21

    You need to change the type of the field IterMut::next to Option<&'a mut Node<T>>:

    pub struct IterMut<'a, T: 'a> {
        next: Option<&'a mut Node<T>>,
    }
    
    impl<'a, T> Iterator for IterMut<'a, T> {
        type Item = &'a mut T;
        fn next(&mut self) -> Option<Self::Item> {
            self.next.take().map(|node| {
                self.next = node.right.0.as_mut().map(|node| &mut **node);
                &mut node.elem
            })
    
        }
    }
    

    You can find more useful information about the implementation of the mutable iterator for recursive data structures in the IterMut chapter of Learning Rust With Entirely Too Many Linked Lists.

    0 讨论(0)
提交回复
热议问题