diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-19 00:47:55 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-19 00:47:55 +0000 |
commit | 26a029d407be480d791972afb5975cf62c9360a6 (patch) | |
tree | f435a8308119effd964b339f76abb83a57c29483 /third_party/rust/derive_more-impl/doc/unwrap.md | |
parent | Initial commit. (diff) | |
download | firefox-26a029d407be480d791972afb5975cf62c9360a6.tar.xz firefox-26a029d407be480d791972afb5975cf62c9360a6.zip |
Adding upstream version 124.0.1.upstream/124.0.1
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'third_party/rust/derive_more-impl/doc/unwrap.md')
-rw-r--r-- | third_party/rust/derive_more-impl/doc/unwrap.md | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/third_party/rust/derive_more-impl/doc/unwrap.md b/third_party/rust/derive_more-impl/doc/unwrap.md new file mode 100644 index 0000000000..e1a103476b --- /dev/null +++ b/third_party/rust/derive_more-impl/doc/unwrap.md @@ -0,0 +1,70 @@ +# What `#[derive(Unwrap)]` generates + +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. +If you don't want the `unwrap_foo` method generated for a variant, you can put the `#[unwrap(ignore)]` attribute on that variant. +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)]`. + + + + +## Example usage + +```rust +# use derive_more::Unwrap; +# +# #[derive(Debug, PartialEq)] +#[derive(Unwrap)] +#[unwrap(ref)] +enum Maybe<T> { + Just(T), + Nothing, +} + +fn main() { + assert_eq!(Maybe::Just(1).unwrap_just(), 1); + + // Panics if variants are different + // assert_eq!(Maybe::<()>::Nothing.unwrap_just(), /* panic */); + // assert_eq!(Maybe::Just(2).unwrap_nothing(), /* panic */); + + assert_eq!((&Maybe::Just(42)).unwrap_just_ref(), &42); +} +``` + + +### What is generated? + +The derive in the above example code generates the following code: +```rust +# enum Maybe<T> { +# Just(T), +# Nothing, +# } +# +impl<T> Maybe<T> { + pub fn unwrap_nothing(self) -> () { + match self { + Maybe::Nothing => (), + _ => panic!(), + } + } + pub fn unwrap_nothing_ref(&self) -> () { + match self { + Maybe::Nothing => (), + _ => panic!(), + } + } + pub fn unwrap_just(self) -> T { + match self { + Maybe::Just(field_0) => field_0, + _ => panic!(), + } + } + pub fn unwrap_just_ref(&self) -> &T { + match self { + Maybe::Just(field_0) => field_0, + _ => panic!(), + } + } +} +``` |