2
2
3
3
## ` if ` expressions
4
4
5
+ > ** <sup >Syntax</sup >**
6
+ > _ IfExpression_ :
7
+ >   ;  ; ` if ` [ _ Expression_ ] <sub >_ except struct expression_ </sub > [ _ BlockExpression_ ]
8
+ >   ;  ; (` else ` (
9
+ > [ _ BlockExpression_ ]
10
+ > | _ IfExpression_
11
+ > | _ IfLetExpression_ ) )<sup >\? </sup >
12
+
5
13
An ` if ` expression is a conditional branch in program control. The form of an
6
14
` if ` expression is a condition expression, followed by a consequent block, any
7
15
number of ` else if ` conditions and blocks, and an optional trailing ` else `
@@ -31,8 +39,18 @@ let y = if 12 * 15 > 150 {
31
39
};
32
40
assert_eq! (y , " Bigger" );
33
41
```
42
+
34
43
## ` if let ` expressions
35
44
45
+ > ** <sup >Syntax</sup >**
46
+ > _ IfLetExpression_ :
47
+ >   ;  ; ` if ` ` let ` _ Pattern_ ` = ` [ _ Expression_ ] <sub >_ except struct expression_ </sub >
48
+ > [ _ BlockExpression_ ]
49
+ >   ;  ; (` else ` (
50
+ > [ _ BlockExpression_ ]
51
+ > | _ IfExpression_
52
+ > | _ IfLetExpression_ ) )<sup >\? </sup >
53
+
36
54
An ` if let ` expression is semantically similar to an ` if ` expression but in
37
55
place of a condition expression it expects the keyword ` let ` followed by a
38
56
refutable pattern, an ` = ` and an expression. If the value of the expression on
@@ -57,3 +75,22 @@ if let ("Ham", b) = dish {
57
75
println! (" Ham is served with {}" , b );
58
76
}
59
77
```
78
+
79
+ ` if ` and ` if let ` expressions can be intermixed:
80
+
81
+ ``` rust
82
+ let x = Some (3 );
83
+ let a = if let Some (1 ) = x {
84
+ 1
85
+ } else if x == Some (2 ) {
86
+ 2
87
+ } else if let Some (y ) = x {
88
+ y
89
+ } else {
90
+ - 1
91
+ };
92
+ assert_eq! (a , 3 );
93
+ ```
94
+
95
+ [ _Expression_ ] : expressions.html
96
+ [ _BlockExpression_ ] : expressions/block-expr.html
0 commit comments