如何正确迭代Rust中多级深度结构的所有记录?

时间:2017-12-13 16:19:31

标签: struct iterator rust

我想知道如何在Rust中正确迭代包含在这样排列的数据结构中的所有结果:

struct Node {
    id: i64,
    nodes: Vec<Node>
}

在此结构中插入的记录具有多个深度级别。类似的东西:

{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: []}
            ]}
        ]}
    ]}
]};

1 个答案:

答案 0 :(得分:2)

我创建了一个简单的递归函数来处理问题,现在一切都很好。当我创建这个主题时,我不知道昨天我的错误是什么。真正的问题与我的要求没有什么不同,但实质是相同的:

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