derive_more icon indicating copy to clipboard operation
derive_more copied to clipboard

An attribute for `TryUnwrap` to simplify its return type

Open rassvet2 opened this issue 2 years ago • 1 comments
trafficstars

I made TryUnwrap returns a dedicated error as Err, but in practice, I guess there are cases where this is not desired. Sometimes, you will only be interested in the input value returned. (And it's exactly me) I think it's a good idea to add an attribute such as #[try_unwrap(simple_return_type)] to make try_unwrap_thing returns Result<(A, B, ...), Self> instead of Result<(A, B, ...), TryUnwrapError<Self>>.

Example

#[derive(TryUnwrap)]
#[try_unwrap(ref, simple_return_type)]
// or #[try_unwrap(simple_error)]
// or #[try_unwrap(return_type = simple)]
// or... #[try_unwrap(return_type = detailed)] to enable TryUnwrapError?
enum Maybe<T> {
    Just(T),
    Nothing
}

fn main() {
    match Maybe::Just("lorem").try_unwrap_nothing() {
        Ok(()) => println!("nothing"),
        Err(val) => println!("{}", val.try_unwrap_just().unwrap()), // => "lorem"
    }
}

rassvet2 avatar Apr 15 '23 15:04 rassvet2

Is it really that big of a deal to access the .input field of the error? I'm not opposed to this though feel free to propose a PR.

JelteF avatar Dec 19 '23 00:12 JelteF