[英]How to implement an iterator of mutable references to the values in the right edges of a Binary Search Tree?
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. 我在Rust中实现了一个简单的二进制搜索树(遵循CIS 198,它很棒),并且为了学习我正在做的迭代器只是通过正确的边缘。
I could not implement an iterator that gives mutable references. 我无法实现一个提供可变引用的迭代器。 I tried a lot of ways, but none were accepted by Rust compiler. 我尝试了很多方法,但Rust编译器都没有接受。 The code I need help is the one below ( while I made a gist with the complete code here ): 我需要帮助的代码是下面的代码( 虽然我在这里给出了完整代码的要点 ):
#[derive(Debug)]
pub struct Tree<T>(Option<Box<Node<T>>>);
#[derive(Debug)]
pub struct Node<T> {
elem: T,
left: Tree<T>,
right: Tree<T>,
}
// MUTABLE BORROW STRUCT
pub struct IterMut<'a, T: 'a> {
next: &'a mut Tree<T>,
}
// MUTABLE BORROW NEXT (I'M STUCK HERE, NOTHING WORKS)
impl<'a, T> Iterator for IterMut<'a, T> {
type Item = &'a mut T;
fn next(&mut self) -> Option<Self::Item> {
// 1 try: cannot infer lifetime
self.next.0.as_mut().map(|node| {
self.next = &mut node.right;
&mut node.elem
})
// 2 try: node.right, node.elem does not live long enough
self.next.0.take().map(|node| {
self.next = &mut node.right;
&mut node.elem
})
}
}
You need to change the type of the field IterMut::next
to Option<&'a mut Node<T>>
: 您需要更改Option<&'a mut Node<T>>
IterMut::next
的字段IterMut::next
的类型:
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 . 您可以在学习Rust与完全太多链接列表的IterMut章节中找到有关递归数据结构的可变迭代器实现的更多有用信息。
我认为你不能将self
分成2个可变对象(一个用于Item
,一个用于self
本身)而不使用一些不安全的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.