gpt4 book ai didi

rust - Rust如何获取从Rust配置 crate 中的配置文件解析出来的内部嵌套结构

转载 作者:行者123 更新时间:2023-12-03 11:48:49 26 4
gpt4 key购买 nike

因此,我是Rust的新手,并尝试修改一些代码以读取具有嵌套值的配置文件,虽然我似乎有数据,但我不确定如何获取内部值。我是否将其返回错误或是否有一些简单的方法来访问我丢失的此结构?

这将编译并显示正确嵌套的值,但是我似乎无法到达Ok()包装器内部。即使只是我应该在“书”中阅读的页码也会有所帮助。

货代

[dependencies]
dirs = "2.0"
config = "0.10"
serde = "1.0"
serde_derive = "1.0"


extern crate dirs;
extern crate config;
extern crate serde;

#[macro_use]
extern crate serde_derive;

use config::{ConfigError, Config, File};

#[derive(Debug, Deserialize)]
struct N4_env_conf {
debug: bool,
thingy: String,
blue: String,
}

#[derive(Debug, Deserialize)]
struct N4_conf {
local: N4_env_conf,
dev: N4_env_conf,
prod: N4_env_conf,
}

impl N4_conf {
pub fn new() -> Result<Self, ConfigError> {
let mut s = Config::new();

s.merge(File::with_name("Settings"))?;
s.try_into()
}
}

fn main() {
let config_dir = format!("{}/.config/n4_config", dirs::home_dir().unwrap().display().to_string());
let settings = N4_conf::new();

println!("{:?}", config_dir);
println!("{:#?}", settings);
}

Settings.toml
[local]
debug = true
thingy = "somethingy"
blue = "greenish"
[dev]
debug = true
thingy = "something"
blue = "green"
[prod]
debug = false
thingy = "otherthing"
blue = "red"

最佳答案

变量settings的类型为Result<N4_conf, ConfigError>。根据N4_conf的结果,该变量可以包含ConfigError类型的N4_conf::new()类型的错误

例子:

match settings {
Ok(conf) => {
println!("local = {:#?}", conf.local);
assert_eq!(conf.local.debug, true);
println!("local.debug = {:?}", conf.local.debug);
println!("local.thingy = {:?}", conf.local.thingy);
println!("local.blue = {:?}", conf.local.blue);

println!("dev = {:#?}", conf.dev);
println!("dev.debug = {:?}", conf.dev.debug);
assert_eq!(conf.dev.debug, true);
println!("dev.thingy = {:?}", conf.dev.thingy);
println!("dev.blue = {:?}", conf.dev.blue);

println!("prod = {:#?}", conf.prod);
assert_eq!(conf.prod.debug, false);
println!("prod.debug = {:?}", conf.prod.debug);
println!("prod.thingy = {:?}", conf.prod.thingy);
println!("prod.blue = {:?}", conf.prod.blue);
}
Err(e) => {
panic!(e);
}
}

看:
  • https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html
  • What's the benefit of using a Result?
  • 关于rust - Rust如何获取从Rust配置 crate 中的配置文件解析出来的内部嵌套结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61966316/

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