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()
?
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 unwrap
ped, then your service would fail in production immediately. This has happened to me, unfortunately.