gpt4 book ai didi

rust - 如何反序列化包含表数组的 TOML 表

转载 作者:行者123 更新时间:2023-12-03 11:33:16 27 4
gpt4 key购买 nike

获取以下 TOML 数据:

[[items]]
foo = 10
bar = 100

[[items]]
foo = 12
bar = 144

还有下面的 rust 代码:

use serde_derive::Deserialize;
use toml::from_str;
use toml::value::Table;

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

fn main() {
let items_string: &str = "[[items]]\nfoo = 10\nbar = 100\n\n[[items]]\nfoo = 12\nbar = 144\n";
let items_table: Table = from_str(items_string).unwrap();
let items: Vec<Item> = items_table["items"].as_array().unwrap().to_vec();
// Uncomment this line to print the table
// println!("{:?}", items_table);
}

如你所见,程序does not compile ,返回这个错误:

expected struct Item, found enum toml::value::Value

我明白它的意思,但我不知道如何解决这个问题并实现我最初想做的事情:将父表的子数组转换为结构数组而不是结构数组表格。

最佳答案

您可以解析为预定义的 TOML 类型,例如 Table,但这些类型不知道预定义类型之外的类型。这些类型主要在数据的实际类型未知或不重要时使用。

在您的情况下,这意味着 TOML Table 类型不知道您的 Item 类型,也无法知道它。

但是您可以轻松地解析为不同的类型:

use serde_derive::Deserialize;
use std::collections::HashMap;
use toml::from_str;

#[derive(Deserialize, Debug)]
struct Item {
foo: u64,
bar: u64,
}

fn main() {
let items_string: &str = "[[items]]\nfoo = 10\nbar = 100\n\n[[items]]\nfoo = 12\nbar = 144\n";
let items_table: HashMap<String, Vec<Item>> = from_str(items_string).unwrap();
let items: &[Item] = &items_table["items"];

println!("{:?}", items_table);
println!("{:?}", items);
}

( Permalink to the playground )

关于rust - 如何反序列化包含表数组的 TOML 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60592561/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com