How to unwrapped Result?

Hello.
How to unwap Result<u32, String>?.
I need print msg or get unwrapped value.

fn is_42(v: u32) -> Result<u32, String>
{
    if v == 42
    {
        return Ok(42);
    }
    
    return Err("Its not 42 blah blah".to_string());
}

fn main()
{
    let fn_err_handling = |x| { 
        println!("Error msg: {:?}", x);
    };

    let res = is_42(23).map_err(fn_err_handling);
    println!("unwraped res : {:?}", res);
    //Res is not unwrapped ;(
}

Playground

https://doc.rust-lang.org/stable/book/ch06-02-match.html

1 Like

I do not understand. Can you give me an example?

So, let's look at your first example here:

    let res = match is_42(23)
    {
        Ok(v) => {v},
        Err(e) => { 
            // when there is an error, we print and return *early*
            // stopping any further execution.
            println!("Error : {:?}", e);
            return;
        }
    };
    
    // If there is an error, we never get here
    println!("unwraped res : {:?}", res);

So, we never get to printing "unwraped res" when there is an error because we are explicitly returning out of the main function with the return keyword.

Now let's look at the second way:

    // We want this to be done on errors
    let fn_err_handling = |x| { 
        println!("Error msg: {:?}", x);
    };

    // What should `res` equal when there's an error ๐Ÿคจ ???
    let res = is_42(23).map_err(fn_err_handling);
    println!("unwraped res : {:?}", res);

The issue with this code is that execution will continue, even when there's an error, because the closure fn_err_handling can't return out of main, because it can only return out of itself.

In other words, what do you want res to equal if there happens to be an error?

If you want to unwrap the value and provide a fallback in the case of an error, you can use unwrap_or_else:

    let fn_err_handling = |x| { 
        println!("Error msg: {:?}", x);
        
        // We must return a value that can be used for
        // res in the event of an error
        0
    };

    let res = is_42(23).unwrap_or_else(fn_err_handling);
    // This will print "unwrapped res : 0"
    println!("unwraped res : {:?}", res);

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.