I would like to know how to iterate correctly in Rust all results contained in a data structure arranged like this:
struct Node {
id: i64,
nodes: Vec<Node>
}
Where the records inserted in this structure have several levels of depth. Something like:
{id: 1, nodes: [
{id: 2, nodes: [
{id: 3, nodes: []},
{id: 4, nodes: []},
{id: 5, nodes: [
{id: 6, nodes: []},
{id: 7, nodes: [
{id: 8, nodes: []},
{id: 9, nodes: []}
]}
]}
]}
]};
I created a simple recursive function to handle the problem and everything is fine now. I do not know what was my mistake yesterday when I created this topic. The real problem is little different from what I asked for, but the essence is the same:
use std::vec::Vec;
struct Node {
id: i64,
nodes: Vec<Node>,
focused: bool,
}
struct Controller {
focused: i32,
}
impl Controller {
fn get_focused(&mut self) -> i32 {
let nodes: Node = ....; // code skipped. represented with JSON object above, but with 'focused' member
for node in nodes.iter() {
self.focused = self.node_iterator(node);
}
self.focused
}
fn node_iterator(&self, node: Node) -> i32 {
let mut focused: i32 = 0;
if node.nodes.len() > 0 {
for n in node.nodes.iter() {
if n.nodes.len() > 0 {
focused = self.node_iterator(n);
if focused > 0 {
return focused;
}
} else {
if n.focused == true {
focused = n.id as i32;
return focused;
}
}
}
}
return 0;
}
}
fn main() {
let mut controller = Controller { focused: 0 };
controller.get_focused();
println!("{}", controller.focused);
}