关于rust:如何使用toml-rs和serde_derive反序列化两种不同的结构和文件格式?

How to deserialize two different structures and file formats using toml-rs and serde_derive?

我正在使用toml-rs和serde_derive反序列化我的应用程序用来描述数据结构的TOML文件。

我可以使用第一个数据结构进行所有工作,第一个数据结构对应一个带有强制性和可选字段的TOML文件定义。

现在,我想使用它来反序列化另一个TOML文件中描述的具有不同字段的另一个数据结构。

如何为反序列化器(我正在使用toml::from_str(&contents))指定要反序列化为哪种结构类型?

相关问题-是否可以将类型放入文件本身,以便反序列化可以更通用,并且反序列化程序可以从文件本身检测要反序列化的类型?


toml::from_str反序列化为表达式期望的类型。 所以

1
let x: Foo = toml::from_str(something)?;

将使用FooDeserialize impl。

您还可以通过通用参数明确指定要反序列化为哪种类型:

1
let x = toml::from_str::<Foo>(something)?;

Also, related - is it possible to put the type into the file itself, so that deserialization can be more generic, and the deserializer can detect the type to deserialize from the file itself?

您可以使用枚举来实现。 每个变体可以容纳不同的类型。 为了弄清楚确切的设计,我建议您为枚举实现Serialize,将其序列化为目标格式,然后您将看到如何执行运行时类型规范。 我不确定toml是否支持枚举,但是json当然可以。