【问题标题】:How do I parse a TOML file with a table at the top level into a Rust structure?如何将带有顶层表的 TOML 文件解析为 Rust 结构?
【发布时间】:2020-01-17 20:23:26
【问题描述】:

例如:

#[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 的意外类型参数的错误。

【问题讨论】:

    标签: rust serde toml


    【解决方案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)?;
    

    【讨论】:

    • 不知道我必须添加一个环绕类型。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-28
    • 1970-01-01
    • 2021-07-12
    相关资源
    最近更新 更多