Statements & expressions

If

  1. a := 10
  2. b := 20
  3. if a < b {
  4. println('$a < $b')
  5. } else if a > b {
  6. println('$a > $b')
  7. } else {
  8. println('$a == $b')
  9. }

if statements are pretty straightforward and similar to most other languages. Unlike other C-like languages, there are no parentheses surrounding the condition and the braces are always required.

if can be used as an expression:

  1. num := 777
  2. s := if num % 2 == 0 { 'even' } else { 'odd' }
  3. println(s)
  4. // "odd"

Type checks and casts

You can check the current type of a sum type using is and its negated form !is.

You can do it either in an if:

  1. struct Abc {
  2. val string
  3. }
  4. struct Xyz {
  5. foo string
  6. }
  7. type Alphabet = Abc | Xyz
  8. x := Alphabet(Abc{'test'}) // sum type
  9. if x is Abc {
  10. // x is automatically casted to Abc and can be used here
  11. println(x)
  12. }
  13. if x !is Abc {
  14. println('Not Abc')
  15. }

or using match:

  1. match x {
  2. Abc {
  3. // x is automatically casted to Abc and can be used here
  4. println(x)
  5. }
  6. Xyz {
  7. // x is automatically casted to Xyz and can be used here
  8. println(x)
  9. }
  10. }

This works also with struct fields:

  1. struct MyStruct {
  2. x int
  3. }
  4. struct MyStruct2 {
  5. y string
  6. }
  7. type MySumType = MyStruct | MyStruct2
  8. struct Abc {
  9. bar MySumType
  10. }
  11. x := Abc{
  12. bar: MyStruct{123} // MyStruct will be converted to MySumType type automatically
  13. }
  14. if x.bar is MyStruct {
  15. // x.bar is automatically casted
  16. println(x.bar)
  17. }
  18. match x.bar {
  19. MyStruct {
  20. // x.bar is automatically casted
  21. println(x.bar)
  22. }
  23. else {}
  24. }

Mutable variables can change, and doing a cast would be unsafe. However, sometimes it’s needed to have a type cast despite of mutability. In this case the developer has to mark the expression with a mut keyword to tell the compiler that you’re aware of what you’re doing.

It works like this:

  1. mut x := MySumType(MyStruct{123})
  2. if mut x is MyStruct {
  3. // x is casted to MyStruct even it's mutable
  4. // without the mut keyword that wouldn't work
  5. println(x)
  6. }
  7. // same with match
  8. match mut x {
  9. MyStruct {
  10. // x is casted to MyStruct even it's mutable
  11. // without the mut keyword that wouldn't work
  12. println(x)
  13. }
  14. }

In operator

in allows to check whether an array or a map contains an element.

  1. nums := [1, 2, 3]
  2. println(1 in nums) // true
  3. m := {'one': 1, 'two': 2}
  4. println('one' in m) // true

It’s also useful for writing boolean expressions that are clearer and more compact:

  1. enum Token {
  2. plus
  3. minus
  4. div
  5. mult
  6. }
  7. struct Parser {
  8. token Token
  9. }
  10. parser := Parser{}
  11. if parser.token == .plus || parser.token == .minus || parser.token == .div || parser.token == .mult {
  12. // ...
  13. }
  14. if parser.token in [.plus, .minus, .div, .mult] {
  15. // ...
  16. }

V optimizes such expressions, so both if statements above produce the same machine code and no arrays are created.

For loop

V has only one looping keyword: for, with several forms.

Array for

  1. numbers := [1, 2, 3, 4, 5]
  2. for num in numbers {
  3. println(num)
  4. }
  5. names := ['Sam', 'Peter']
  6. for i, name in names {
  7. println('$i) $name') // Output: 0) Sam
  8. } // 1) Peter

The for value in arr form is used for going through elements of an array. If an index is required, an alternative form for index, value in arr can be used.

Note, that the value is read-only. If you need to modify the array while looping, you have to use indexing:

  1. mut numbers := [0, 1, 2]
  2. for i, _ in numbers {
  3. numbers[i]++
  4. }
  5. println(numbers) // [1, 2, 3]

When an identifier is just a single underscore, it is ignored.

Map for

  1. m := {'one':1, 'two':2}
  2. for key, value in m {
  3. println("$key -> $value") // Output: one -> 1
  4. } // two -> 2

Either key or value can be ignored by using a single underscore as the identifer.

  1. m := {'one':1, 'two':2}
  2. // iterate over keys
  3. for key, _ in m {
  4. println(key) // Output: one
  5. } // two
  6. // iterate over values
  7. for _, value in m {
  8. println(value) // Output: 1
  9. } // 2

Range for

  1. // Prints '01234'
  2. for i in 0 .. 5 {
  3. print(i)
  4. }

low..high means an exclusive range, which represents all values from low up to but not including high.

Condition for

  1. mut sum := 0
  2. mut i := 0
  3. for i <= 100 {
  4. sum += i
  5. i++
  6. }
  7. println(sum) // "5050"

This form of the loop is similar to while loops in other languages. The loop will stop iterating once the boolean condition evaluates to false. Again, there are no parentheses surrounding the condition, and the braces are always required.

Bare for

  1. mut num := 0
  2. for {
  3. num += 2
  4. if num >= 10 {
  5. break
  6. }
  7. }
  8. println(num) // "10"

The condition can be omitted, resulting in an infinite loop.

C for

  1. for i := 0; i < 10; i += 2 {
  2. // Don't print 6
  3. if i == 6 {
  4. continue
  5. }
  6. println(i)
  7. }

Finally, there’s the traditional C style for loop. It’s safer than the while form because with the latter it’s easy to forget to update the counter and get stuck in an infinite loop.

Here i doesn’t need to be declared with mut since it’s always going to be mutable by definition.

Labelled break & continue

break and continue control the innermost for loop by default. You can also use break and continue followed by a label name to refer to an outer for loop:

  1. outer: for i := 4; true; i++ {
  2. println(i)
  3. for {
  4. if i < 7 {
  5. continue outer
  6. } else {
  7. break outer
  8. }
  9. }
  10. }

The label must immediately precede the outer loop. The above code prints:

  1. 4
  2. 5
  3. 6
  4. 7

Match

  1. os := 'windows'
  2. print('V is running on ')
  3. match os {
  4. 'darwin' { println('macOS.') }
  5. 'linux' { println('Linux.') }
  6. else { println(os) }
  7. }

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.

  1. number := 2
  2. s := match number {
  3. 1 { 'one' }
  4. 2 { 'two' }
  5. else { 'many' }
  6. }

A match expression returns the final expression from each branch.

  1. enum Color {
  2. red
  3. blue
  4. green
  5. }
  6. fn is_red_or_blue(c Color) bool {
  7. return match c {
  8. .red, .blue { true } // comma can be used to test multiple values
  9. .green { false }
  10. }
  11. }

A match statement can also be used to branch on the variants of an enum by using the shorthand .variant_here syntax. An else branch is not allowed when all the branches are exhaustive.

  1. c := `v`
  2. typ := match c {
  3. `0`...`9` { 'digit' }
  4. `A`...`Z` { 'uppercase' }
  5. `a`...`z` { 'lowercase' }
  6. else { 'other' }
  7. }
  8. println(typ)
  9. // 'lowercase'

You can also use ranges as match patterns. If the value falls within the range of a branch, that branch will be executed.

Note that the ranges use ... (three dots) rather than .. (two dots). This is because the range is inclusive of the last element, rather than exclusive (as .. ranges are). Using .. in a match branch will throw an error.

Note: match as an expression is not usable in for loop and if statements.

Defer

A defer statement defers the execution of a block of statements until the surrounding function returns.

  1. import os
  2. fn read_log() {
  3. mut ok := false
  4. mut f := os.open('log.txt') or { panic(err) }
  5. defer {
  6. f.close()
  7. }
  8. // ...
  9. if !ok {
  10. // defer statement will be called here, the file will be closed
  11. return
  12. }
  13. // ...
  14. // defer statement will be called here, the file will be closed
  15. }