Skip to content

Commit 7775157

Browse files
authored
Merge pull request #1185 from peter-kehl/1184
For #1184 closes #1184
2 parents 68ea088 + c75b3d4 commit 7775157

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

src/flow_control/if_let.md

+20
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,26 @@ fn main() {
9494
}
9595
```
9696

97+
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.
98+
99+
Would you like a challenge? Fix the following example to use `if let`:
100+
101+
```rust,editable,ignore
102+
// This enum purposely doesn't #[derive(PartialEq)],
103+
// neither we implement PartialEq for it. That's why comparing Foo::Bar==a fails below.
104+
enum Foo {Bar}
105+
106+
fn main() {
107+
let a = Foo::Bar;
108+
109+
// Variable a matches Foo::Bar
110+
if Foo::Bar == a {
111+
// ^-- this causes a compile-time error. Use `if let` instead.
112+
println!("a is foobar");
113+
}
114+
}
115+
```
116+
97117
### See also:
98118

99119
[`enum`][enum], [`Option`][option], and the [RFC][if_let_rfc]

0 commit comments

Comments
 (0)