Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

If and if let grammar #137

Merged
merged 1 commit into from
Dec 1, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions src/expressions/if-expr.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@

## `if` expressions

> **<sup>Syntax</sup>**
> _IfExpression_ :
> &nbsp;&nbsp; `if` [_Expression_]<sub>_except struct expression_</sub> [_BlockExpression_]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we link to the struct expression here?

> &nbsp;&nbsp; (`else` (
> [_BlockExpression_]
> | _IfExpression_
> | _IfLetExpression_ ) )<sup>\?</sup>

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`
Expand Down Expand Up @@ -31,8 +39,18 @@ let y = if 12 * 15 > 150 {
};
assert_eq!(y, "Bigger");
```

## `if let` expressions

> **<sup>Syntax</sup>**
> _IfLetExpression_ :
> &nbsp;&nbsp; `if` `let` _Pattern_ `=` [_Expression_]<sub>_except struct expression_</sub>
> [_BlockExpression_]
> &nbsp;&nbsp; (`else` (
> [_BlockExpression_]
> | _IfExpression_
> | _IfLetExpression_ ) )<sup>\?</sup>

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
Expand All @@ -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