Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does dotenv().ok() do?

I am using the Diesel ORM wrapper with PostgreSQL. I was following the guide on their website which has the following code:

pub fn establish_connection() -> PgConnection {
     dotenv().ok();

     let database_url = env::var("DATABASE_URL")
         .expect("DATABASE_URL must be set");
     PgConnection::establish(&database_url)
         .expect(&format!("Error connecting to {}", database_url))
}

I understood what dotenv() does through the dotenv docs — it loads the env file. In the source code I saw that that dotenv() returns a Result. What does ok() do then? Does it unwrap the result? If so, why not use unwrap()?

like image 730
elementory Avatar asked Jun 24 '20 01:06

elementory


1 Answers

It's a way to ignore errors arising from failing to load the dotenv environment file.

dotenv() returns a Result. Result::ok converts the Result into an Option. This Option does not trigger the warning about an unused Result.

why not use unwrap()

Because you don't want it to fail. In production, you should not have an environment file, instead you will use actual environment variables. If you unwrapped, then your service would fail in production immediately. This has happened to me, unfortunately.

like image 174
Shepmaster Avatar answered Nov 16 '22 03:11

Shepmaster