confy icon indicating copy to clipboard operation
confy copied to clipboard

Get part result from default()

Open ziyouwa opened this issue 2 years ago • 0 comments

Result is None when test.toml is blank. I wish to get as below, how can I do it?

Some(
    Test {
        sub: Some(
            [
                Data {
                    id: 2,
                    name: "3",
                },
                Data {
                    id: 4,
                    name: "5",
                },
            ],
        ),
    },
)

my code is here:

testconfig.rs:

use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
pub struct Data {
    pub id: usize,
    pub name: String,
}
impl Default for Data {
    fn default() -> Self {
        Self {
            id: 1,
            name: "test1".to_string(),
        }
    }
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Test {
    #[allow(dead_code)]
    pub sub: Option<Vec<Data>>,
}
impl Default for Test {
    fn default() -> Self {
        Self { sub: Some(vec![Data{id:2,name: "3".to_string()}, Data{id:4, name: "5".to_string()}]) }
    }
}
#[derive(Debug, Serialize, Deserialize)]
pub struct TestGlobalConfig {
    #[allow(dead_code)]
    pub test: Option<Test>,
}
impl Default for TestGlobalConfig {
    fn default() -> Self {
        Self { test: Some(Test::default()) }
    }
}

main.rs:

use std::sync::RwLock;
pub mod testconfig;
use crate::testconfig::TestGlobalConfig;
lazy_static::lazy_static! {
    static ref GLOBAL: RwLock<TestGlobalConfig> ={
        let path = concat!(env!("CARGO_MANIFEST_DIR"),"/test.toml");
        if let Ok(global_config) = confy::load_path::<TestGlobalConfig>(path) { 
            RwLock::new(global_config)
        } else {
            panic!("load config file {path:?} error!");
        }
    };
}
fn main() {
    let binding = GLOBAL.read().unwrap();
    let settings = &binding.test;
    println!("{:#?}", settings);
}

ziyouwa avatar Jul 30 '23 06:07 ziyouwa