如何解析 Rust 中结构未知的 TOML?

Kon*_*ner 4 rust toml

我的配置文件中有大量任意键值对,我想使用 toml 板条箱对其进行解析。然而,标准方法似乎是使用适合配置文件的给定结构。如何将键值对加载到映射或对迭代器等数据结构中,而不必预先使用结构体指定结构?

pro*_*-fh 7

toml作为Value可以容纳任何内容的结构,您可以动态内省以发现任何内容,而无需强制使用特定结构。

use toml::Value;

fn show_value(
    value: &Value,
    indent: usize,
) {
    let pfx = "  ".repeat(indent);
    print!("{}", pfx);
    match value {
        Value::String(string) => {
            println!("a string --> {}", string);
        }
        Value::Integer(integer) => {
            println!("an integer --> {}", integer);
        }
        Value::Float(float) => {
            println!("a float --> {}", float);
        }
        Value::Boolean(boolean) => {
            println!("a boolean --> {}", boolean);
        }
        Value::Datetime(datetime) => {
            println!("a datetime --> {}", datetime);
        }
        Value::Array(array) => {
            println!("an array");
            for v in array.iter() {
                show_value(v, indent + 1);
            }
        }
        Value::Table(table) => {
            println!("a table");
            for (k, v) in table.iter() {
                println!("{}key {}", pfx, k);
                show_value(v, indent + 1);
            }
        }
    }
}

fn main() {
    let input_text = r#"
    abc = 123
    [def]
      ghi = "hello"
      jkl = [ 12.34, 56.78 ]
    "#;
    let value = input_text.parse::<Value>().unwrap();
    show_value(&value, 0);
}
/*
a table
key abc
  an integer --> 123
key def
  a table
  key ghi
    a string --> hello
  key jkl
    an array
      a float --> 12.34
      a float --> 56.78
*/
Run Code Online (Sandbox Code Playgroud)