From 0ea18a78cf90f64004c54fc3589b57844d78561f Mon Sep 17 00:00:00 2001 From: Peter Kehl Date: Tue, 23 Apr 2019 21:30:39 -0700 Subject: [PATCH 1/2] For https://github.com/rust-lang/rust-by-example/issues/1184 --- src/flow_control/if_let.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/flow_control/if_let.md b/src/flow_control/if_let.md index 450354af42..9b93a273a3 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 +// 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] From c75b3d49116c93b0d0fa6139883d5adceff738f2 Mon Sep 17 00:00:00 2001 From: Peter Kehl Date: Wed, 24 Apr 2019 11:07:11 -0700 Subject: [PATCH 2/2] Added "ignore" for an example that is supposed to fail compilation --- src/flow_control/if_let.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/flow_control/if_let.md b/src/flow_control/if_let.md index 9b93a273a3..ffbf0da989 100644 --- a/src/flow_control/if_let.md +++ b/src/flow_control/if_let.md @@ -98,7 +98,7 @@ Another benefit: `if let` allows to match enum non-parameterized variants, even Would you like a challenge? Fix the following example to use `if let`: -```rust,editable +```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}