如何将具有顶层表的TOML文件解析为Rust结构?

时间:2020-01-17 20:23:26

标签: rust serde toml

例如:

#[macro_use]
extern crate serde_derive;
extern crate toml;

#[derive(Deserialize)]
struct Entry {
    foo: String,
    bar: String,
}

let toml_string = r#"
  [[entry]]
  foo = "a0"
  bar = "b0"

  [[entry]]
  foo = "a1"
  bar = "b1"
  "#;
let config: toml::value::Table<Entry> = toml::from_str(&toml_string)?;

但是,这不起作用,并且会引发有关Table的意外类型参数的错误。

1 个答案:

答案 0 :(得分:1)

打印任意已解析的值会显示您具有的结构:

let config: toml::Value = toml::from_str(&toml_string)?;
println!("{:?}", config)

重新格式化的输出显示您有一个具有单个键entry的表,该表是具有键foobar的表的数组:

Table({
  "entry": Array([
    Table({
      "bar": String("b0"),
      "foo": String("a0")
    }),
    Table({
      "bar": String("b1"),
      "foo": String("a1")
    })
  ])
})

反序列化时,您需要匹配以下结构:

#[derive(Debug, Deserialize)]
struct Outer {
    entry: Vec<Entry>,
}

#[derive(Debug, Deserialize)]
struct Entry {
    foo: String,
    bar: String,
}
let config: Outer = toml::from_str(&toml_string)?;