The query mark ?
operator is used for early exit an operate with return sort that is appropriate with the worth of the ?
is used on. Equivalent to Err(e)
however not many individuals know it may be used on None
as nicely.
The ?
operator is usually used with Consequence<T, E>
to propagate error up the decision chain. We will outline a unified error enum to host all errors. Bear in mind to make the most of Rust’s conversion technique From<T>
to solid international errors into the unified error enum. That manner, we make the most of ?
operator, it’ll carry out the conversion behind the scene.
// Unified `Error` enum
#[derive(Debug)]
enum Error {
ParseIntError(std::num::ParseIntError),
ParseFloatError(std::num::ParseFloatError),
}
impl std::fmt::Show for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Consequence {
match self {
Self::ParseIntError(e) => write!(f, "ParseIntError: {}", e.to_string()),
Self::ParseFloatError(e) => write!(f, "ParseFloatError: {}", e.to_string()),
}
}
}
impl std::error::Error for Error {}
// Convert `std::num::ParseIntError` to `Error`
impl From<std::num::ParseIntError> for Error {
fn from(err: std::num::ParseIntError) -> Self {
Self::ParseIntError(err)
}
}
// Convert `std::num::ParseFloatError` to `Error`
impl From<std::num::ParseFloatError> for Error {
fn from(err: std::num::ParseFloatError) -> Self {
Self::ParseFloatError(err)
}
}
fn important() -> Consequence<(), Error> {
// Parse an integer and unwrap it, or throw `Error::ParseIntError`
let _: i32 = "123".parse()?;
let _: i32 = "not_an_integer".parse()?;
// Parse a float and unwrap it, or throw `Error::ParseFloatError`
let _: f64 = "not_a_number".parse()?;
Okay(())
}
The ?
operator might additionally carry out early return on Choice<T>
return sort.
fn get_first_char_of_second_word(phrase: &str) -> Choice<char> {
// Return `None` if the phrase encompass a single phrase
phrase.cut up(" ").skip(1).subsequent()?.chars().subsequent()
}
fn important() {
assert_eq!(get_first_char_of_second_word("Good day World"), Some('W'));
assert_eq!(get_first_char_of_second_word("Good day?"), None);
}