Change my Mind: Rust should use the `¿` operator to early return on Ok(_) / Some(_) values.
We all know and love the Try operator ?. With #![feature(try_trait_v2)] we can implement this operator very nicely for our own types. For example we can define this CursedResult that returns early with ? when an Ok(_) value appears:
enum CursedResult<T, E> {
Ok(T),
Err(E),
}
impl<T, E> Try for CursedResult<T, E> {
type Output = E;
type Residual = T;
fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
match self {
CursedResult::Ok(ok) => ControlFlow::Break(ok),
CursedResult::Err(err) => ControlFlow::Continue(err),
}
}
fn from_output(output: Self::Output) -> Self {
CursedResult::Err(output)
}
}
impl<T, E> FromResidual<T> for CursedResult<T, E> {
fn from_residual(residual: T) -> Self {
CursedResult::Ok(residual)
}
}
It might be used like this:
pub fn search_for_file() -> CursedResult<File, &'static str> {
check_lru_cache()?;
check_file_system()?;
check_remote_server()?;
CursedResult::Err("not found.")
}
However what if we do not want to bind the early return behavior to a type, but decide on a per call basis which variant should return early?
This is where the ¿ operator could come it: The logical opposite of the ? operator.
Also it looks funny.