如何在Rust中正确迭代多级深度结构的所有记录? [英] How to correctly iterate all records of a multi-level depth structure in Rust?
本文介绍了如何在Rust中正确迭代多级深度结构的所有记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道如何在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: []}
]}
]}
]}
]};
推荐答案
我创建了一个简单的递归函数来处理该问题,现在一切都很好.我不知道昨天创建这个主题时我犯了什么错误.真正的问题与我要求的没什么不同,但本质是相同的:
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);
}
这篇关于如何在Rust中正确迭代多级深度结构的所有记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文