The question mark operator exists so that you don't have to check if a result is an Err
, then return it every time you want to propagate an error to the previous function.
I would imagine that the inverse would also be true. Some operator that checks if a result is an Ok
, then returns it.
I realize that it would be used less than the ?
but it would still be a nice tool to have.
Here is an example of some code that would do well with the Ok operator.
fn combined_function(input: u32) -> Result<bool, String> {
let r = is_not_modN(input, 3);
if r.is_ok() {
return r;
}
let r = is_not_modN(input, 5);
if r.is_ok() {
return r;
}
let r = is_not_modN(input, 7);
if r.is_ok() {
return r;
}
Err(String::from("Invalid number. It is devisable by either 3, 5, or 7!!"))
}
fn is_not_modN(input: u32, n: u32) -> Result<bool, ()> {
if input%n != 0 {
Ok(true)
} else {
Err(())
}
}
Given on Ok
operator (I will use #
for brevity), the code is a LOT shorter and easier to read.
fn combined_function(input: u32) -> Result<bool, String> {
is_not_modN(input, 3)#;
is_not_modN(input, 5)#;
is_not_modN(input, 7)#;
Err(String::from("Invalid number. It is devisable by either 3, 5, or 7!!"))
}
fn is_not_modN(input: u32, n: u32) -> Result<bool, ()> {
if input%n != 0 {
Ok(true)
} else {
Err(())
}
}
Is there anything like this in Rust already? And if there isn't, what would be the reasons for not adding this? (other than, cases like this being more rare than cases where ?
can be used)