1

I do check function results on assignment using match statement. In some cases I want to exit the program with an error message like panic!() does. But how can I create a function or macro that can be used everywhere?

Example:

let args = match args::Args::parse() {
    Ok(args) => args,
    Err(e) => someerror("bla")
};
let mut statedoc = match state_loader.load() {
    Ok(states) => states,
    Err(e) => someerror("blub")
};

What does someerror() need to return to work everywhere?

3
  • someerror doesn't need to return anything, but its implementation can panic or print an error and exit the process. In other words, you can call panic!(s) inside someerror or, if you don't want your program to panic, you can call eprintln!("{}", s); std::process::exit(1);. Commented Aug 31, 2020 at 12:21
  • No, Rust will not compile this because the return type of someerror() doesn't match. Commented Aug 31, 2020 at 13:12
  • That depends on the return type - see dianhenglau's answer. Commented Aug 31, 2020 at 13:19

2 Answers 2

6

One way is to use diverging function. Use the following syntax:

fn someerror(msg: &str) -> ! { // Note the `-> !` here
    eprintln!("Error: {}", msg);
    panic!();
}

fn main() {
    let r: Result<i32, &str> = Err("hello");
    let x = match r {
        Ok(x) => x,
        Err(e) => someerror(e),
    };
    println!("x = {}", x);
}
Sign up to request clarification or add additional context in comments.

Comments

1

Remember that main can return a Result and you can use the ?-operator everywhere:

fn foo() -> Result<i32, &'static str> {
    Err("Nope!")
}

fn main() -> Result<(), &'static str> {
    let x = 5 * foo()?;
    println!("{}", x);
    Ok(())
}

When executed, the above program will just print "Error: Nope!" and have an exit status not equal to zero. To support more kinds of errors, you can have a a custom enum to wrap those and appropriate implementations of Into, so you can just do let args = args::Args::parse()?;. Any errors will bubble up to main() and cause the error to be printed out.

1 Comment

But than I have to implement every type. I don't think panic!() does it this way as it cannot know every type.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.