Mastodon Default environment variables in Rust

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: rust, programming, tutorial

Want to learn Rust and offensive security? Take a look at my book Black Hat Rust. All early-access supporters get a special discount and awesome bonuses: https://academy.kerkour.com/black-hat-rust?coupon=BLOG.
Warning: this offer is limited in time!

Related posts