Figment Layered Environment Config
Compose application configuration with figment layers, joining TOML files with environment overrides and strict extraction.
Code
use figment::{
providers::{Env, Format, Serialized, Toml},
Figment,
};
use serde::{Deserialize, Serialize};
use std::time::Duration;
#[derive(Debug, Serialize, Deserialize, Clone)]
struct DatabaseConfig {
url: String,
pool_size: u32,
connect_timeout_ms: u64,
}
#[derive(Debug, Serialize, Deserialize)]
struct AppConfig {
environment: String,
port: u16,
database: DatabaseConfig,
}
fn layered_config() -> Result<AppConfig, figment::Error> {
let defaults = AppConfig {
environment: "development".into(),
port: 3000,
database: DatabaseConfig {
url: "postgres://localhost/app".into(),
pool_size: 8,
connect_timeout_ms: 3000,
},
};
Figment::from(Serialized::defaults(defaults)) // 内置默认值打底
.merge(Toml::file("config/app.toml")) // 配置文件覆盖
.merge(Env::prefixed("APP_").split("__")) // 环境变量压顶
.extract()
}
fn main() {
// APP_DATABASE__URL 等:双下划线映射嵌套键
std::env::set_var("APP_ENVIRONMENT", "production");
std::env::set_var("APP_DATABASE__POOL_SIZE", "24");
match layered_config() {
Ok(config) => {
println!(
"{} on port {} -> {} (pool {})",
config.environment,
config.port,
config.database.url,
config.database.pool_size
);
let timeout = Duration::from_millis(config.database.connect_timeout_ms);
println!("connect timeout: {timeout:?}");
}
Err(err) => {
// extract 失败会报告具体哪个字段在哪个层出了问题
eprintln!("config error: {err}");
}
}
}What the code does
Figment Layered Environment Config comes down to the functions layered_config and main.
Result turns the error into data — visible in the type, handled by the caller. The match covers the value’s shapes one arm at a time — nothing falls to a default by accident.
What to watch for
- Requires
figment::andserde::as packages; the snippet will not run without them. - The
Resultvalues will not let errors pass silently; each must be matched, unwrapped, or propagated.
Using it
The main signature reads fn layered_config() -> Result<AppConfig, figment::Error>
Running the file prints labeled results such as connect timeout: — each operation’s effect is visible in the output.
The sequence layered_config lives in main; running the file triggers it.
Key statements
Ok(config) => {
println!(
"{} on port {} -> {} (pool {})",
config.environment,
config.port,
config.database.url,
config.database.pool_size
);
let timeout = Duration::from_millis(config.database.connect_timeout_ms);
println!("connect timeout: {timeout:?}");
}
Err(err) => {
// extract 失败会报告具体哪个字段在哪个层出了问题
eprintln!("config error: {err}");
}
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- How should callers handle failures?
- As `Result` values — each fallible call returns one, and the caller matches or propagates it.
- Does this require external packages?
- Yes — `figment::` and `serde::`. Add them to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.