Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to handle ? operator in Rust in cases where function return type can't be Result<T, E>

I was reading THE BOOK about the ? operator and wanted to use it in a function which doesn’t have a Result<T, E> type. Below mentioned part was written in it

The other technique is to use a match or one of the Result<T, E> methods to handle the Result<T, E> in whatever way is appropriate

I saw no implementation of this and simply writing match before the statement with ? doesn’t work.
How do I catch that error and use it to return some other dependent value for my function.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My code looked something like this (obv. it didn’t run)… I’m not really interested in other way to achieve the same functionality, instead I’m asking if it’s possible to use this particular operator with this specific config.

fn error_handling() -> String{

    //the ? operator (replaces the try macro)
    //Shorthand, passes the Ok() value out while returns the Err() value.
    //Also can pass the Some() value from Option<T> and return None value.
    //
    //If function doesn't have the return type as Result<T, E> then either extract
    //the value out of Ok with a match statement or change the Return type in code.


    let mut result = String::new();

    let file_return = match fs::File::open("something.txt")? {
        Ok(data) => data.read_to_string(&mut result),
        Err(_) => &result.clear()
    }
    result
}

>Solution :

How do I catch that error and use it to return some other dependent value for my function.

Just remove the ?. expr? is essentially just this:

match expr {
    Ok(v) => v,
    Err(e) => return Err(e)
}

It performs an "immediate return" of an error if there’s one, and otherwise lets you use the unwrapped value. So the type of

fs::File::open("something.txt")?

is File, not Result<File, ...>. Therefore the match is not valid anymore.

Incidentally, the match you’re writing here you originally wrote exists in the standard library, it’s called expect, so you can pretty much just write

fs::File::new("something.txt").expect("something bad happened")

The new version also has a built-in shortcut (kinda): std::fs::read_to_string.

read_to_string("something.txt").unwrap_or_else(String::new)

should be equivalent to the code you wrote.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading