Rust 实现迭代器

Rust Implement Iterator

所以我目前正在学习 Rust,并且对如何实现非消耗迭代器有疑问。 我编写了一个堆栈:

struct Node<T>{
    data:T,
    next:Option<Box<Node<T>>>
}
pub struct Stack<T>{
    first:Option<Box<Node<T>>>
}
impl<T> Stack<T>{
    pub fn new() -> Self{
        Self{first:None}
    }
    pub fn push(&mut self, element:T){
        let old = self.first.take();
        self.first = Some(Box::new(Node{data:element, next:old}));
    }
    pub fn pop(&mut self) -> Option<T>{
        match self.first.take(){
            None => None,
            Some(node) =>{
                self.first = node.next;
                Some(node.data)
            }
        }
    }
    pub fn iter(self) -> StackIterator<T>{
        StackIterator{
            curr : self.first
        }
    }
}
pub struct StackIterator<T>{
    curr : Option<Box<Node<T>>>
}
impl<T> Iterator for StackIterator<T>{
    type Item = T;
    fn next (&mut self) -> Option<T>{
        match self.curr.take(){
            None => None,
            Some(node) => {
                self.curr = node.next;
                Some(node.data)
            }
        }
    }
}

使用堆栈迭代器,它是在堆栈上调用 iter() 方法创建的。问题:我不得不让这个 iter() 方法消耗它的堆栈,因此堆栈只能迭代一次。如何在不使用 Stack 且不实现复制或克隆特征的情况下实现此方法?

感谢您的帮助,对于这个非常基本的问题深表歉意:)

How can I implement this method without consuming the Stack and without implementing the copy or clone trait?

让 StackIterator 借用 堆栈,迭代器 return 引用项目。类似于

impl<T> Stack<T>{
    pub fn iter(&self) -> StackIterator<T>{
        StackIterator{
            curr : &self.first
        }
    }
}
pub struct StackIterator<'stack, T: 'stack>{
    curr : &'stack Option<Box<Node<T>>>
}
impl<'s, T: 's> Iterator for StackIterator<'s, T>{
    type Item = &'s T;
    fn next (&mut self) -> Option<&'s T>{
        match self.curr.as_ref().take() {
            None => None,
            Some(node) => {
                self.curr = &node.next;
                Some(&node.data)
            }
        }
    }
}

(我没有实际测试这段代码,所以它可能不起作用)

这基本上就是 std::iter::Iter 所做的(尽管它是作为 way 较低级别实现的)。

说的是通过实现链表来学习 Rust probably isn't the best idea in the world,链表是退化图,借用检查器与图的关系不是很友好。