I can not for the life of me figure this one out.
It feels like I'm trying to create a linked list... maybe I am, I don't know.
Kind of a flat_map too...
What I want is to have a struct that holds "something" and also children of the same, if any. The "something" can be a String for now, so we can print it and see if the logic is working.
I want to be able to hit .next() (in the future, .prev() also) directly on the root struct and it return me a reference (can be mutable) to the next element. So we can do things, such as print the String that it holds. the .next() function should be recursive however and iterate its children also.
Note, I don't need it to necessarily impl iterator. I tried many times not to though. And my strategy might be entirely wrong. So it's important that I can just get what I want
Here's where I got to:
struct Step {
name: String,
children: Vec<Box<Step>>,
child_iter: Box<dyn Iterator<Item = Self>>,
}
impl Step {
fn new(name: String) -> Self {
let children = vec![];
let child_iter = Box::new(children.iter());
Self {
name,
children,
child_iter,
}
}
fn with_child(mut self, step: Step) -> Self {
self.children.push(Box::new(step));
self
}
}
impl Iterator for Step {
type Item = Self;
fn next(&mut self) -> Option<Self::Item> {
todo!()
}
}
impl Display for Step {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "({})", self.name)
}
}
fn main() {
let a = Step::new("A".to_string());
let b = Step::new("B".to_string())
.with_child(Step::new("1".to_string()))
.with_child(Step::new("2".to_string()))
.with_child(Step::new("3".to_string()));
let c = Step::new("C".to_string());
let mut wizard = Step::new("MAIN".to_string())
.with_child(a)
.with_child(b)
.with_child(c);
for w in wizard {
println!("{}", step);
}
}
Thanks for your help. (i'm gonna head to bed now, I'll reply in the morning. Thanks in advance!!)