I want to get a value from Option<T> if it is Some(T), or from Result<T, E> if it is None.
Currently, I'm using a temporary struct and passing it to Option::ok_or to convert Option<T> to Result<T, E> as follows.
fn run_app(db_path: Option<PathBuf>) -> Result<(), Box<dyn std::error::Error>> {
struct TempError;
let db_path: PathBuf = db_path
// Convert Option<PathBuf> to Result<PathBuf, TempError>.
.ok_or(TempError)
// Convert Result<PathBuf, TempError> to Result<PathBuf, my_app::InvalidEnvVarError>.
// Return from this function if it is Err(my_app::InvalidEnvVarError).
.or_else(|_| database_path_from_env())?;
// Now db_path is PathBuf.
// Open and process the database
// ...
Ok(())
}
fn database_path_from_env() -> Result<PathBuf, my_app::InvalidEnvVarError> {
std::env::var("MY_APP_DATABASE")
.map(PathBuf::from)
.map_err(|_| my_app::InvalidEnvVarError)
}
Is there any way to achieve this in a more straightforward way without using a temporary struct?