Search…
Match

The match statement

A match statement is a short-hand way for if - else. If the input is matched the statement block of the first matching branch will be executed and its last expression will be returned. The else branch will be executed when there is no other matching branch.
1
num := 1
2
match num % 2 == 0 {
3
true { print('The input number is even.') }
4
else { print('The input number is odd.') }
5
}
Copied!
One can also initialize variables using match to have different values according to a condition.
1
num := 3
2
s := match num {
3
1 { 'one' }
4
2 { 'two' }
5
else {
6
'many'
7
}
8
}
Copied!
Examples:
1
fn even(num int) bool {
2
match num % 2 == 0 {
3
true { print('The input number is even.') }
4
else { print('The input number is odd.') }
5
}
6
}
7
8
fn num_to_str(num int) int {
9
match num {
10
1 { 'one' }
11
2 { 'two' }
12
else {
13
'many'
14
}
15
}
16
}
17
18
fn main() {
19
println(even(14)) // 'The input number is even.'
20
println(even(3)) // 'The input number is odd.'
21
println(num_to_str(1)) // 'one'
22
println(num_to_str(2)) // 'two'
23
println(num_to_str(352)) // 'many'
24
}
Copied!

Enums

One can also match on enum values (variants) as branches by using the .variant_here syntax:
1
enum Animal {
2
cat
3
dog
4
goldfish
5
pig
6
}
7
8
fn makes_miau(a Animal) bool {
9
return match a {
10
.cat { true }
11
else { false }
12
}
13
}
14
15
fn is_land_creature(a Animal) bool {
16
return match a {
17
.cat { true }
18
.dog { true }
19
.pig { true }
20
else {
21
false
22
}
23
}
24
}
25
// OR LIKE THAT
26
fn is_land_creature_alt(a Animal) bool {
27
return match a {
28
.goldfish { false }
29
else {
30
true
31
}
32
}
33
}
34
35
fn main() {
36
my_cat := Animal.cat
37
my_goldfish := Animal.goldfish
38
39
println(makes_miau(my_cat)) // true
40
println(is_land_creature(my_cat)) // true
41
println(is_land_creature(my_goldfish)) // false
42
}
Copied!

Exercises

  1. 1.
    Write a V program that creates an array of all even numbers from 1 to 50.
  2. 2.
    Write a V program that, given an array of numbers, returns the maximum value.
  3. 3.
    Write a V program that determines whether color (enum) is red or blue