doc: update `match` docs (#5753)

pull/5723/head
Nick Treleaven 2020-07-08 14:56:49 +01:00 committed by GitHub
parent 5ea17ad2d4
commit ec82fa77c5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 17 additions and 11 deletions

View File

@ -652,7 +652,13 @@ match os {
'linux' { println('Linux.') } 'linux' { println('Linux.') }
else { println(os) } else { println(os) }
} }
```
A match statement is a shorter way to write a sequence of `if - else` statements.
When a matching branch is found, the following statement block will be run.
The else branch will be run when no other branches match.
```v
number := 2 number := 2
s := match number { s := match number {
1 { 'one' } 1 { 'one' }
@ -661,9 +667,7 @@ s := match number {
} }
``` ```
A match statement is a shorter way to write a sequence of `if - else` statements. A match expression returns the final expression from each branch.
When a matching branch is found, the following statement block will be run, and the final expression will be returned.
The else branch will be evaluated when no other branches match.
```v ```v
enum Color { enum Color {
@ -674,15 +678,16 @@ enum Color {
fn is_red_or_blue(c Color) bool { fn is_red_or_blue(c Color) bool {
return match c { return match c {
.red { true } .red { true }
.blue { true } .blue { true }
else { false } .green { false }
} }
} }
``` ```
A match statement can also be used to branch on the variants of an `enum` A match statement can also be used to branch on the variants of an `enum`
by using the shorthand `.variant_here` syntax. by using the shorthand `.variant_here` syntax. An `else` branch is not allowed
when all the branches are exhaustive.
### Defer ### Defer
@ -1287,12 +1292,13 @@ fn pass_time(w World) {
Mars { w.shiver() } Mars { w.shiver() }
else {} else {}
} }
// using `as` to specify a variable name // using `as` to specify a name for each value
match w as expr { match w as var {
Venus { expr.sweat() } Mars { var.shiver() }
Venus { var.sweat() }
else { else {
// w is of type World // w is of type World
assert w !is Venus assert w is Moon
} }
} }
} }