if let
For some use cases, when matching enums, match is awkward. For example:
1. // Make `optional` of type `Option<i32>`
2. let optional = Some(7);
4. match optional {
5. Some(i) => {
6. println!("This is a really long string and `{:?}`", i);
7. // ^ Needed 2 indentations just so we could destructure
8. // `i` from the option.
9. },
10. _ => {},
11. // ^ Required because `match` is exhaustive. Doesn't it seem
12. // like wasted space?
13. };
if let is cleaner for this use case and in addition allows various
failure options to be specified:
1. fn main() {
2. // All have type `Option<i32>`
3. let number = Some(7);
4. let letter: Option<i32> = None;
5. let emoticon: Option<i32> = None;
7. // The `if let` construct reads: "if `let` destructures `number` into
8. // `Some(i)`, evaluate the block (`{}`).
9. if let Some(i) = number {
10. println!("Matched {:?}!", i);
11. }
13. // If you need to specify a failure, use an else:
14. if let Some(i) = letter {
15. println!("Matched {:?}!", i);
16. } else {
17. // Destructure failed. Change to the failure case.
18. println!("Didn't match a number. Let's go with a letter!");
19. };
21. // Provide an altered failing condition.
22. let i_like_letters = false;
24. if let Some(i) = emoticon {
25. println!("Matched {:?}!", i);
26. // Destructure failed. Evaluate an `else if` condition to see if the
27. // alternate failure branch should be taken:
28. } else if i_like_letters {
29. println!("Didn't match a number. Let's go with a letter!");
30. } else {
31. // The condition evaluated false. This branch is the default:
32. println!("I don't like letters. Let's go with an emoticon :)!");
33. };
34. }
In the same way, if let can be used to match any enum value:
1. // Our example enum
2. enum Foo {
3. Bar,
4. Baz,
5. Qux(u32)
6. }
8. fn main() {
9. // Create example variables
10. let a = Foo::Bar;
11. let b = Foo::Baz;
12. let c = Foo::Qux(100);
14. // Variable a matches Foo::Bar
15. if let Foo::Bar = a {
16. println!("a is foobar");
17. }
19. // Variable b does not match Foo::Bar
20. // So this will print nothing
21. if let Foo::Bar = b {
22. println!("b is foobar");
23. }
25. // Variable c matches Foo::Qux which has a value
26. // Similar to Some() in the previous example
27. if let Foo::Qux(value) = c {
28. println!("c is {}", value);
29. }
30. }
