Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get error using if else method in rust?

I know the idiomatic way to handle errors in rust is using match statement but I am looking for other ways to do the same.

use std::fs;

fn main() {
    if let Ok(f) = fs::read_dir("/dummy"){
        println!("First: {:?}", f);
    }else{
        println!("Error");
    }
    
}

This works but I need the original Result error from fs::read_dir("/dummy") to be printed in the else statement. How can I do it?

like image 333
Eka Avatar asked Sep 05 '25 00:09

Eka


2 Answers

Generally, I'd consider such an approach a bad idea, but you do have a few options, the most obvious two being "multiple if lets" and a "functional style" approach. I've included the match version for comparison. The code is available on the playground.

fn multiple_if_lets() {
    let f = std::fs::read_dir("/dummy");
    if let Ok(f) = &f {
        println!("First: {:?}", f);
    }
    if let Err(f) = &f {
        println!("Error: {:?}", f);
    }
}

fn functional_style() {
    std::fs::read_dir("/dummy")
        .map(|f| println!("First: {:?}", f))
        .unwrap_or_else(|f| println!("Error: {:?}", f));
}

fn match_style() {
    match std::fs::read_dir("/dummy") {
        Ok(f) => println!("First: {:?}", f),
        Err(f) => println!("Error: {:?}", f),
    }
}
like image 72
Michael Anderson Avatar answered Sep 07 '25 19:09

Michael Anderson


Since Rust 1.65.0 (Nov. 2022), as mentioned by Mara Bos, you can do:

let Ok(f) = fs::read_dir("/dummy") else{ println!("Error"); return };
println!("First: {:?}", f);

let-else statements.

You can now write things like:

let Ok(a) = i32::from_str("123") else { return };

without needing an if or match statement.
This can be useful to avoid deeply nested if statements.

like image 41
VonC Avatar answered Sep 07 '25 20:09

VonC