From b451229dd17f7c5129b481d402430778edd951d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Br=C3=A1ulio=20Bezerra?= Date: Sat, 14 Oct 2017 12:30:45 -0300 Subject: [PATCH] If and if let grammar --- src/expressions/if-expr.md | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/src/expressions/if-expr.md b/src/expressions/if-expr.md index 585f316c4..c8f57f077 100644 --- a/src/expressions/if-expr.md +++ b/src/expressions/if-expr.md @@ -2,6 +2,14 @@ ## `if` expressions +> **Syntax** +> _IfExpression_ : +>    `if` [_Expression_]_except struct expression_ [_BlockExpression_] +>    (`else` ( +> [_BlockExpression_] +> | _IfExpression_ +> | _IfLetExpression_ ) )\? + An `if` expression is a conditional branch in program control. The form of an `if` expression is a condition expression, followed by a consequent block, any number of `else if` conditions and blocks, and an optional trailing `else` @@ -31,8 +39,18 @@ let y = if 12 * 15 > 150 { }; assert_eq!(y, "Bigger"); ``` + ## `if let` expressions +> **Syntax** +> _IfLetExpression_ : +>    `if` `let` _Pattern_ `=` [_Expression_]_except struct expression_ +> [_BlockExpression_] +>    (`else` ( +> [_BlockExpression_] +> | _IfExpression_ +> | _IfLetExpression_ ) )\? + An `if let` expression is semantically similar to an `if` expression but in place of a condition expression it expects the keyword `let` followed by a refutable pattern, an `=` and an expression. If the value of the expression on @@ -57,3 +75,22 @@ if let ("Ham", b) = dish { println!("Ham is served with {}", b); } ``` + +`if` and `if let` expressions can be intermixed: + +```rust +let x = Some(3); +let a = if let Some(1) = x { + 1 +} else if x == Some(2) { + 2 +} else if let Some(y) = x { + y +} else { + -1 +}; +assert_eq!(a, 3); +``` + +[_Expression_]: expressions.html +[_BlockExpression_]: expressions/block-expr.html