Default environment variables in Rust

Rust does not provide a built-in way to set a default environment variable. Yet, it's easy to achieve with the unwrap_or combinator.

fn main() {
    let port = std::env::var("PORT").unwrap_or("8080".to_string());
}

Alternatively, you can define a function that sets a default env value if none is set.

fn set_default_env_var(key: &str, value: &str) {
    if std::env::var(key).is_err() {
        std::env::set_var(key, value);
    }
}

fn main() {
    set_default_env_var("PORT", "8080");

    let port = std::env::var("PORT").unwrap();

    println!("{}", port);
}
$ cargo run
8080
1 email / week to learn how to (ab)use technology for fun & profit: Programming, Hacking & Entrepreneurship.
I hate spam even more than you do. I'll never share your email, and you can unsubscribe at any time.

Tags: programming, rust, tutorial

Want to learn Rust, Cryptography and Security? Get my book Black Hat Rust!