Skip to content
Sword

Control flow

if needs no parentheses and always needs braces:

func classify(n int) int {
if n < 0 {
return -1
} else if n == 0 {
return 0
}
return 1
}
func main() int {
return classify(7) + classify(-3) + 42
}

When one value is being compared against several, switch says so more directly than a chain of if:

func statusText(code u64) string {
switch code {
case 200:
return "OK"
case 400, 404, 405:
return "your fault"
case 500:
return "my fault"
default:
return "unknown"
}
}
func main() int {
return int(statusText(404).len) + 32
}

One case per value, several values per case, and no fallthrough — a case body ends where the next case begins. The subject can be an integer, a bool, a string or an enum. Two cases matching the same value is an error, because one of them could never run.

A switch is not a loop, so break and continue inside one speak to the loop around it. There is nothing to break out of: a case body ends on its own.

for has four forms and no others:

func main() int {
mut sum := 0
for i in 0..5 { // a range
sum += i
}
for v in [3]int{1, 2, 3} { // the elements of a slice, array or string
sum += v
}
mut n := 0
for n < 3 { // a condition
n += 1
sum += n
}
for { // forever, until something leaves
sum += 1
if sum > 20 {
break
}
}
return sum
}

The element form binds a copy, so writing to it changes nothing behind it. When you need the position too, bind both:

import "std/io"
func main() !int {
words := [3]string{"ada", "grace", "alan"}
for i, w in words {
try io.Printf("{}: {}\n", i, w)
}
return 0
}

There is a fifth form, for part in xs.chunks(n), but it exists for concurrency and is covered there.