If I have simple tree like structure:
struct Foo {
description: String,
childs: Vec<Foo>,
}
there is simple way to implement read-only iterator for it:
struct LinearContentIterator<'a> {
stack: Vec<&'a Foo>,
}
impl<'a> LinearContentIterator<'a> {
fn new(root: &'a Foo) -> LinearContentIterator<'a> {
let mut stack = Vec::with_capacity(100);
stack.push(root);
LinearContentIterator { stack }
}
}
impl<'a> Iterator for LinearContentIterator<'a> {
type Item = &'a Foo;
fn next(&mut self) -> Option<Self::Item> {
let item: Self::Item = self.stack.pop()?;
for entry in item.childs.iter().rev() {
self.stack.push(&*entry);
}
Some(item)
}
}
but how should I implement mutable iterator, that allows change only description
field in it?
The obvious way is not possible to compile, because of it takes two mut reference,
plus if it is possible to compile, I can see how to disable the way to change tree structure during iteration?
struct LinearContentIterator<'a> {
stack: Vec<&'a mut Foo>,
}
impl<'a> LinearContentIterator<'a> {
fn new(root: &'a mut Foo) -> LinearContentIterator<'a> {
let mut stack = Vec::with_capacity(100);
stack.push(root);
LinearContentIterator { stack }
}
}
impl<'a> Iterator for LinearContentIterator<'a> {
type Item = &'a mut Foo;
fn next(&mut self) -> Option<Self::Item> {
let item: Self::Item = self.stack.pop()?;
for entry in item.childs.iter_mut().rev() {
self.stack.push(&mut *entry);
}
Some(item)
}
}