← 中文资源

简体中文版本

match 递归遍历 JSON Value

match 递归解构 Value 枚举:数组与对象逐层缩进打印,键值对保持插入顺序,直到每个叶子节点都被访问,展示嵌套模式匹配的完整形态。summarize 给六个变体各一条臂,Array 逐项 depth+1,Object 先打印键、值按 depth+2 下钻,缩进宽度直接取自 depth。

阅读英文原文

实现说明

逻辑集中在函数 summarize、main里。 这个示例中仅有的重复出现在 for item in items 里。输入的每种形态各占一个 match 分支,编译器检查这套分支是否完整。

使用要点

  • main 的演示流程是 summarize——跑一遍文件,这条流程从头到尾可见。

常见问题

「match 递归遍历 JSON Value」这个示例怎么运行?

文件自包含:直接运行,没有需要预先安装的依赖。

主签名形如 fn summarize(value: &Value, depth: usize)

核心语句

Value::Object(pairs) => {
    println!("{:indent$}object len {}", "", pairs.len(), indent = depth * 2);
    for (key, nested) in pairs {
        println!("{:indent$}key {key}:", "", indent = (depth + 1) * 2);
        summarize(nested, depth + 2);
    }
}
Value::Array(items) => {
    println!("{:indent$}array len {}", "", items.len(), indent = depth * 2);
    for item in items {
        summarize(item, depth + 1);
    }
}

代码示例

#[derive(Debug)]
enum Value {
    Null,
    Bool(bool),
    Number(f64),
    Text(String),
    Array(Vec<Value>),
    Object(Vec<(String, Value)>),
}

// match walks the JSON-like tree recursively, one arm per shape
fn summarize(value: &Value, depth: usize) {
    match value {
        Value::Null => println!("{:indent$}null", "", indent = depth * 2),
        Value::Bool(flag) => println!("{:indent$}bool {flag}", "", indent = depth * 2),
        Value::Number(n) => println!("{:indent$}number {n}", "", indent = depth * 2),
        Value::Text(s) => println!("{:indent$}text {s:?} ({})", "", s.len(), indent = depth * 2),
        Value::Array(items) => {
            println!("{:indent$}array len {}", "", items.len(), indent = depth * 2);
            for item in items {
                summarize(item, depth + 1);
            }
        }
        Value::Object(pairs) => {
            println!("{:indent$}object len {}", "", pairs.len(), indent = depth * 2);
            for (key, nested) in pairs {
                println!("{:indent$}key {key}:", "", indent = (depth + 1) * 2);
                summarize(nested, depth + 2);
            }
        }
    }
}

fn main() {
    let config = Value::Object(vec![
        ("retries".into(), Value::Number(3.0)),
        ("verbose".into(), Value::Bool(true)),
        ("tags".into(), Value::Array(vec![Value::Text("eu".into()), Value::Text("prod".into())])),
        ("cache".into(), Value::Object(vec![("ttl".into(), Value::Number(30.0))])),
        ("marker".into(), Value::Null),
    ]);
    summarize(&config, 0);
}