Assign the Ok result from a Result to a variable or print the Error message

Hello,

I have a question about properly handling errors when trying to assign the result of a function to a variable.
I have something like this

let status = match command.status() {
    Ok(result) => result, // I want to assign the result to the variable
    Err(err) => Err(err) // Or print the error and set the variable to -1
};

I am trying to execute a command that the user has entered, for example pwd, and get the status code of the execution. The problem is that the user can enter some nonsense and this will result in an error when I try to execute the command. In this case I want to print the error message, No such file or directory and set the status variable to something.

What is the proper way of doing that?

I managed to get this to work. Was wondering if it's a correct way of doing it:

match command.status() {
        Ok(result) => match result.code() {
            Some(code)  => code,
            None        => -1,
        },
        Err(err) => { println!("{:?}", err); 0 }
    }

Yes, that's correct. You can slightly simplify it with result.code().unwrap_or(-1) instead of the second match.

2 Likes