| 1 |
# What `#[derive(Unwrap)]` generates |
| 2 |
|
| 3 |
When an enum is decorated with `#[derive(Unwrap)]`, for each variant `foo` in the enum, with fields `(a, b, c, ...)` a public instance method `unwrap_foo(self) -> (a, b, c, ...)` is generated. |
| 4 |
If you don't want the `unwrap_foo` method generated for a variant, you can put the `#[unwrap(ignore)]` attribute on that variant. |
| 5 |
If you want to treat a reference, you can put the `#[unwrap(ref)]` attribute on the enum declaration or that variant, then `unwrap_foo_ref(self) -> (&a, &b, &c, ...)` will be generated. You can also use mutable references by putting `#[unwrap(ref_mut)]`. |
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
## Example usage |
| 11 |
|
| 12 |
```rust |
| 13 |
# use derive_more::Unwrap; |
| 14 |
# |
| 15 |
# #[derive(Debug, PartialEq)] |
| 16 |
#[derive(Unwrap)] |
| 17 |
#[unwrap(ref)] |
| 18 |
enum Maybe<T> { |
| 19 |
Just(T), |
| 20 |
Nothing, |
| 21 |
} |
| 22 |
|
| 23 |
fn main() { |
| 24 |
assert_eq!(Maybe::Just(1).unwrap_just(), 1); |
| 25 |
|
| 26 |
// Panics if variants are different |
| 27 |
// assert_eq!(Maybe::<()>::Nothing.unwrap_just(), /* panic */); |
| 28 |
// assert_eq!(Maybe::Just(2).unwrap_nothing(), /* panic */); |
| 29 |
|
| 30 |
assert_eq!((&Maybe::Just(42)).unwrap_just_ref(), &42); |
| 31 |
} |
| 32 |
``` |
| 33 |
|
| 34 |
|
| 35 |
### What is generated? |
| 36 |
|
| 37 |
The derive in the above example code generates the following code: |
| 38 |
```rust |
| 39 |
# enum Maybe<T> { |
| 40 |
# Just(T), |
| 41 |
# Nothing, |
| 42 |
# } |
| 43 |
# |
| 44 |
impl<T> Maybe<T> { |
| 45 |
pub fn unwrap_nothing(self) -> () { |
| 46 |
match self { |
| 47 |
Maybe::Nothing => (), |
| 48 |
_ => panic!(), |
| 49 |
} |
| 50 |
} |
| 51 |
pub fn unwrap_nothing_ref(&self) -> () { |
| 52 |
match self { |
| 53 |
Maybe::Nothing => (), |
| 54 |
_ => panic!(), |
| 55 |
} |
| 56 |
} |
| 57 |
pub fn unwrap_just(self) -> T { |
| 58 |
match self { |
| 59 |
Maybe::Just(field_0) => field_0, |
| 60 |
_ => panic!(), |
| 61 |
} |
| 62 |
} |
| 63 |
pub fn unwrap_just_ref(&self) -> &T { |
| 64 |
match self { |
| 65 |
Maybe::Just(field_0) => field_0, |
| 66 |
_ => panic!(), |
| 67 |
} |
| 68 |
} |
| 69 |
} |
| 70 |
``` |