Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
637 views
in Technique[技术] by (71.8m points)

struct - How to correctly iterate all records of a multi-level depth structure in Rust?

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: []}
            ]}
        ]}
    ]}
]};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...