How to set_default() using config-rs crate

How to set_default() using config-rs crate

(Jin Qing's Column, Nov., 2024)

config is a configuration system for Rust applications.

Example of examples\hierarchical-env:

rust 复制代码
#[derive(Debug, Deserialize)]
#[allow(unused)]
struct Database {
    url: String,
}

#[derive(Debug, Deserialize)]
#[allow(unused)]
pub(crate) struct Settings {
    debug: bool,
    database: Database,
}

impl Settings {
    pub(crate) fn new() -> Result<Self, ConfigError> {
        let s = Config::builder()
            .add_source(File::with_name("examples/hierarchical-env/config/default"))
            .build()?;

        // You can deserialize (and thus freeze) the entire configuration as
        s.try_deserialize()
    }
}

ConfigBuilder::set_default sets a default value at key:

rust 复制代码
pub fn set_default<S, T>(self, key: S, value: T) -> Result<Self, ConfigError>
where
    S: AsRef<str>,
    T: Into<Value>,

Such as:

rust 复制代码
        let s = Config::builder()
            .set_default("debug", true)?
            ...

But how to set a member like Database struct?

rust 复制代码
        let s = Config::builder()
            .set_default("database", Database{url: "".into()})?
            ...

fails:

error[E0277]: the trait bound `ValueKind: From<Database>` is not satisfied
   --> examples\hierarchical-env\settings.rs:50:38
    |
50  |             .set_default("database", Database{url: "".into()})?
    |              -----------             ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `From<Database>` is not implemented for `ValueKind`, which is required by `Database: Into<Value>`
    |              |
    |              required by a bound introduced by this call
    |
    = help: the following other types implement trait `From<T>`:
              <ValueKind as From<&'a str>>
              ...
              <ValueKind as From<i32>>
            and 9 others
    = note: required for `Database` to implement `Into<ValueKind>`
    = note: required for `Value` to implement `From<Database>`
    = note: 1 redundant requirement hidden
    = note: required for `Database` to implement `Into<Value>`
note: required by a bound in `ConfigBuilder::<St>::set_default`
   --> D:\github\config-rs\src\builder.rs:156:12
    |
153 |     pub fn set_default<S, T>(mut self, key: S, value: T) -> Result<Self>
    |            ----------- required by a bound in this associated function
...
156 |         T: Into<Value>,
    |            ^^^^^^^^^^^ required by this bound in `ConfigBuilder::<St>::set_default`

The above links suggest to use ValueKind:

        let s = Config::builder()
            .set_default(
                "database",
                ValueKind::Table(HashMap::<String, Value>::from([("url".into(), "".into())])),
            )?
            ...

The ergonomic way is to implement From<Database> for ValueKind:

rust 复制代码
impl From<Database> for ValueKind {
    fn from(value: Database) -> Self {
        let t = HashMap::<String, Value>::from([("url".into(), value.url.into())]);
        ValueKind::Table(t)
    }
}
rust 复制代码
        let s = Config::builder()
            .set_default("database", Database { url: "".into() })?
            ...

For nested struct:

rust 复制代码
#[derive(Debug, Default, Deserialize)]
#[allow(unused)]
struct Database {
    url: String,
    other: Other,
}

#[derive(Debug, Default, Deserialize)]
#[allow(unused)]
struct Other {}

impl From<Database> for ValueKind {
    fn from(value: Database) -> Self {
        let t = HashMap::<String, Value>::from([
            ("url".into(), value.url.into()),
            ("other".into(), value.other.into()),
        ]);
        ValueKind::Table(t)
    }
}

impl From<Other> for ValueKind {
    fn from(_value: Other) -> Self {
        ValueKind::Table(HashMap::new())
    }
}
rust 复制代码
        let s = Config::builder()
            .set_default("database", Database::default())?
            ...
相关推荐
编程星空4 小时前
css主题色修改后会多出一个css吗?css怎么定义变量?
开发语言·后端·rust
Hello.Reader11 小时前
深入理解 Rust 的 `Rc<T>`:实现多所有权的智能指针
开发语言·后端·rust
yoona102011 小时前
Rust编程语言入门教程(八)所有权 Stack vs Heap
开发语言·后端·rust·区块链·学习方法
guyoung13 小时前
DeepSeek轻量级本地化部署工具——AIMatrices DeepSeek
rust·llm·deepseek
JD技术委员会18 小时前
Rust 语法噪音这么多,是否适合复杂项目?
开发语言·人工智能·rust
Hello.Reader18 小时前
Rust 中的 `Drop` 特性:自动化资源清理的魔法
开发语言·rust·自动化
Vitalia18 小时前
从零开始学 Rust:基本概念——变量、数据类型、函数、控制流
开发语言·后端·rust
cheungxiongwei.com18 小时前
Rust 驱动的 Python 工具革命:Ruff 和 uv 与传统工具的对比分
python·rust·uv
wzhao10118 小时前
elf_loader:一个使用Rust编写的ELF加载器
linux·rust·gnu
泡泡Java20 小时前
使用WebStorm开发Vue3项目
ide·rust·webstorm