Use the serde and serde_derive crates to automatically validate configuration values by defining a struct with #[derive(Deserialize)] and parsing your config file into it. This approach ensures that if the configuration format is invalid or types don't match, the program fails to compile or returns a clear error at runtime instead of crashing later.
use serde::Deserialize;
#[derive(Deserialize)]
struct Config {
port: u16,
host: String,
}
fn main() {
let config_str = r#"{ "port": 8080, "host": "localhost" }"#;
let config: Config = serde_json::from_str(config_str).expect("Invalid config");
println!("Config loaded: {:?}", config);
}