6
votes

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()?

1
see the docs for the standard lib version. diesel's will probably be defined in terms of that. The ok method will probably do the same. unwrap can panic, but ok can't, so the caller can handle the failure case - joel
@joelb Note that the use of ok() is not for handling the failure case, it's for ignoring the failure case. When handling failure, one would not typically call ok() (because it throws away the error information), but match the returned Result directly. - user4815162342

1 Answers

6
votes

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.