Skip to content

Commit

Permalink
match expressions take 2 (FuelLabs#1355)
Browse files Browse the repository at this point in the history
* match expressions take 2

* fix directory

* match statements

* formatting editor fix

* fmt

Co-authored-by: SilentCicero <>
Co-authored-by: Mohammad Fawaz <[email protected]>
  • Loading branch information
SilentCicero and mohammadfawaz authored May 6, 2022
1 parent c158ef7 commit 0bfaa66
Show file tree
Hide file tree
Showing 4 changed files with 75 additions and 0 deletions.
8 changes: 8 additions & 0 deletions docs/src/basics/control_flow.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,14 @@ let my_data = if some_bool < 10 { foo() } else { bar() };

Note that all branches of the `if` expression must return a value of the same type.

### `match` expressions

Sway supports advanced pattern matching through exhaustive `match` expressions.

```sway
{{#include ../../../examples/match_statements/src/main.sw}}
```

## Loops

### `while`
Expand Down
11 changes: 11 additions & 0 deletions examples/match_statements/Forc.lock
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[[package]]
name = 'core'
dependencies = []

[[package]]
name = 'match_statements'
dependencies = ['std']

[[package]]
name = 'std'
dependencies = ['core']
8 changes: 8 additions & 0 deletions examples/match_statements/Forc.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[project]
authors = ["Fuel Labs <[email protected]>"]
entry = "main.sw"
license = "Apache-2.0"
name = "match_statements"

[dependencies]
std = { path = "../../sway-lib-std" }
48 changes: 48 additions & 0 deletions examples/match_statements/src/main.sw
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
script;

fn foo() {
// do something
}
fn bar() {
// do something
}

fn main() -> u64 {
let x = 5;

// Match as an expression.
let a = match 8 {
7 => {
4
},
9 => {
5
},
8 => {
6
},
_ => {
100
},
};

// Match as a statement for control flow.
match x {
5 => {
foo()
},
_ => {
bar()
},
};

// Match as expression used for a return.
match 42 {
0 => {
24
},
foo => {
foo
},
}
}

0 comments on commit 0bfaa66

Please sign in to comment.