1

I'm trying to return a Result from a function and extract it's return. I'm using i32 and a &str and I get a mismatch type error in the match statment (Can't use two different types in a match). How do I fix this?

fn use_result(par: i32)-> Result<i32, &'static str> {
    if par == 0 {
        Err("some error")                                                
    } else {               
        println!("par is 1");                                            
        Ok(par)            
    }
              
}        
fn main() {
    // Result
    let res = match use_result(1) {
        Ok(v) => v,
        Err(e) => e,
    };
}
//Do something with res: v or res: e

}

1 Answer 1

3

In Rust, every variable has a single type. In the code you have now, res is either a &'static str or an i32, which is not allowed.

Your options are:

Return early

fn main() {
  let res: i32 = match use_result(1) {
    Ok(v) => v,
    Err(e) => return,
  };
}

Different code in each match arm

fn main() {
  match use_result(1) {
    Ok(v) => {
      handle_success(v);
    },
    Err(e) => {
      handle_error(e);
    },
  };
}

Return an enum

Enums allow you to express that a type is "one of these possible variants" in a type safe way:

enum IntOrString {
  Int(i32),
  String(&'static str),
}

fn main() {
  let i_or_s: IntOrString = match use_result(1) {
    Ok(v) => IntOrString::Int(v),
    Err(e) => IntOrString::String(e),
  };
}

But this is a bit weird, since Result<i32, &'static str> is already an enum, if you want to do anything with an IntOrString you'll need to match on it later on (or an if let, etc).

Panic

fn main() {
  let res: i32 = match use_result(1) {
    Ok(v) => v,
    Err(e) => panic!("cannot be zero"),
  };
}

This is more cleanly expressed as use_result(1).unwrap(). It's usually not what you want, since it doesn't allow the caller of the function to recover/handle the error. But if you're calling this from main(), the error has nowhere else to propagate to, so unwrapping is usually OK.

2
  • Do only reasonable I see is your second option, but then if I want to log the error, I will have to define some mutable value outside the scope of the match and make the error equal to it in the arm. I'm guessing I should use an enum or even struct for the error variable. Am I correct?
    – docHoliday
    Feb 25, 2022 at 15:05
  • If you want to log the error then quit the program, you can just have eprintln!("{}, e); return; as the body of that match arm (i.e. after Err(e) => {) Feb 25, 2022 at 15:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.