I want to return an error from a function in case a condition is true:
use std::error::Error;
pub fn run() -> Result<(), Box> {
//
A Result
is an enum with two variants. To return either of them, you just use corresponding variants.
fn foo(var: bool) -> Result<(), i32> {
if var {
Ok(()) //in fact this is std::result::Result::Ok
} else {
Err(-3) //in fact this is std::result::Result::Err
}
}
The reason why you don't have to write std::result::Result::Ok
is that it is in the prelude. As you can see, you don't have to stick to Box
, but can return any type you want. It is a generic enum, with no restrictions.
The ?
-operator is a handy shortcut for early returns, so you don't have to be too verbose about results.