tl;dr Is it possible to extend std::result::Result
to add my own variant that signals "things are Okay but also..." and keep impl Result
methods like is_ok()
?
I want to extend Result
to signal additional states that a function caller can use for special cases.
use std::result::Result
use std::io::Error;
/// Extend Result to also signal "things are okay but check on things"
enum ResultExt<T, E> {
Result<T, E>,
OkButCheckThings(T),
}
pub fn do_stuff() -> ResultExt<u64, Error> {
// ...
}
pub fn main() -> {
let var = match do_stuff() {
Ok(val) => { val },
Err(err) => { 0 },
OkButCheckThings(val) => { check_things(); val },
}
dbg!(var);
}
It's possible to plainly extend an Enum
. But I would also like to use the underlying Result<T, E>
functions like is_ok
.
let var2 = do_stuff();
if var2.is_ok() {
println!("It is totally Ok, nothing to check!");
}
I created a rust playground example that successfully extends Result<T, E>
but the extended enum
cannot use functions like is_ok()
.
The real-world use-case is a function that calls std::io::Read
may need to "modify" the returned Result
to signal additional states beyond Ok
and Err
. But I want these various "meta states" to be captured by one enum
, as opposed to returning various other bool
flags (I want to avoid return signature with (Result<T>, bool, bool)
. This would allow one clean match
statement of all possible states; Ok
, Err
, "Okay but..."
, "Err but ..."
, etc..