diff --git a/src/flow_control/if_let.md b/src/flow_control/if_let.md index 450354af42..ffbf0da989 100644 --- a/src/flow_control/if_let.md +++ b/src/flow_control/if_let.md @@ -94,6 +94,26 @@ fn main() { } ``` +Another benefit: `if let` allows to match enum non-parameterized variants, even if the enum doesn't `#[derive(PartialEq)]`, neither we implement `PartialEq` for it. In such case, classic `if Foo::Bar==a` fails, because instances of such enum are not comparable for equality. However, `if let` works. + +Would you like a challenge? Fix the following example to use `if let`: + +```rust,editable,ignore +// This enum purposely doesn't #[derive(PartialEq)], +// neither we implement PartialEq for it. That's why comparing Foo::Bar==a fails below. +enum Foo {Bar} + +fn main() { + let a = Foo::Bar; + + // Variable a matches Foo::Bar + if Foo::Bar == a { + // ^-- this causes a compile-time error. Use `if let` instead. + println!("a is foobar"); + } +} +``` + ### See also: [`enum`][enum], [`Option`][option], and the [RFC][if_let_rfc]