toml crate 如何构造类似依赖关系的结构

toml crate how to structure dependencies-like struct

我有一个格式为的 toml 文件:

[general]

loaded=true
can_reload=true

[dependencies]

dependencies 部分与 Cargo.toml 依赖项的工作方式基本相同,每个依赖项都在单独的行中列出。

问题是,当使用 toml crate 到 serialize/deserialize 时,我不确定如何指定一个部分,该部分可以在其下方包含任意数量的条目和任意名称。

我的结构目前看起来像:

#[derive(Debug, Serialize, Deserialize)]
pub struct Configuration {
    general: ConfigurationGeneral,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ConfigurationGeneral {
    loaded: bool,
    can_reload: bool,
}

我在文档中看到您可以使用 Option 但这仍然只是针对单个值。我无法知道依赖项的名称以及将它们添加到结构中的数量。

HashMap 表示 dependencies:

use std::collections::HashMap;

use serde::{Serialize, Deserialize}; // 1.0.126
use toml; // 0.5.8

#[derive(Debug, Serialize, Deserialize)]
pub struct Configuration {
    general: ConfigurationGeneral,
    dependencies: HashMap<String, String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ConfigurationGeneral {
    loaded: bool,
    can_reload: bool,
}

fn main() {
    let config: Configuration = toml::from_str(r#"
        [general]
        loaded = true
        can_reload = true
        
        [dependencies]
        toml = "1.4"
    "#).unwrap();
    
    println!("{:#?}", config);
}

playground 上查看。

这里我只是将值的依赖关系解析为 Strings 但它们当然也可以是更复杂的结构。