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

后端 未结 2 1904
孤独总比滥情好
孤独总比滥情好 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:21

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

    pub struct IterMut<'a, T: 'a> {
        next: Option<&'a mut Node>,
    }
    
    impl<'a, T> Iterator for IterMut<'a, T> {
        type Item = &'a mut T;
        fn next(&mut self) -> Option {
            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.

提交回复
热议问题