How to Load Environment Variables in Rust (.env)? 🦀

September 20, 2022 ¿Ves algún error? Corregir artículo rust-wallpaper

One of my weekend programming languages is Rust and something I needed when I started was to use environment variables, so I'm leaving you a small tutorial on how to use these variables.

1. Creating Our Project

For this we'll use cargo

~
cargo new rust-env

This will create a generated file structure that will look like this:

src

main.rs

target

.gitignore

Cargo.lock

Cargo.toml

2. Adding Dependencies

Inside the Cargo.toml file we'll add the following line of code to the dependencies.

~
[dependencies] dotenv="*"

3. Loading Our .env File

For this we'll first create our .env file in the project root.

~
touch .env

And we'll add the following environment variables.

~
DB_USER="root" DB_PASSWORD="root123"

And now inside our src/main.rs file we'll load our variables.

src/main.rs
dotenv::from_path("./.env").expect("error loading env");

4. Using Environment Variables

Now using Rust's standard library for environment variables we'll retrieve our environment variables as follows.

src/main.rs
let db_users = env::var("DB_USER").expect("env error"); let db_password = env::var("DB_PASSWORD").expect("env error");

And we'll print them to verify we achieved our goal.

src/main.rs
println!("------------------------"); println!("DB_USER: {}", db_users); println!("DB_PASSWORD: {}", db_password); println!("------------------------");

5. Running Our Example

We use cargo to run our example

~
cargo run --package rust-env --bin rust-env
 $ DB_USER:  root $ DB_PASSWORD:  root123

I hope this tutorial helps you and that you start using this fun language more. Soon I'll be uploading more Rust-related tutorials.

Here you can find the repository rust-env

Until next time 👋