How can I implement this method without consuming the Stack and without implementing the copy or clone trait?
Have StackIterator borrow the stack instead, and the iterator return references to the items. Something along the lines of
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)
}
}
}
}
(I didn't actually test this code so it's possible it doesn't work)
That's essentially what std::iter::Iter
does (though it's implemented as a way lower level).
That said learning Rust by implementing linked lists probably isn't the best idea in the world, linked lists are degenerate graphs, and the borrow checker is not on very friendly terms with graphs.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…