例如:
#[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
的意外类型参数的错误。
答案 0 :(得分:1)
打印任意已解析的值会显示您具有的结构:
let config: toml::Value = toml::from_str(&toml_string)?;
println!("{:?}", config)
重新格式化的输出显示您有一个具有单个键entry
的表,该表是具有键foo
和bar
的表的数组:
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)?;