[Go] Flow Control

For loop

for loop is the only looping construct in Go.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
func main() {
sum := 0
for i := 0; i < 10; i++ {
sum += i
}
fmt.Println(sum)
}

// The init and post statements are optional\
func main() {
sum := 1
for ; sum < 1000; {
sum += sum
}
fmt.Prinln(sum)
}

// Use for like "while"
func main() {
sum := 1
for sum < 1000 {
sum += sum
}
fmt.Println(sum)
}

// infinite loop
func main() {
for {
}
}

If

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
func sqrt(x float64) string {
if x < 0 {
return sqrt(-x) + "i"
}
return fmt.Sprint(math.Sqrt(x))
}

// Start with a short statement
func pow(x, n, lim float64) float64 {
if v := math.Pow(x, y); v < lim {
return v
} else {
fmt.Printf("%g >= %g\n", v, lim)
}
return lim
}

Switch

Go’s switch is like the one in C, C++, Java, JavaScript, and PHP, except that Go only runs the selected case, not all the cases that follow. In effect, the break statement that is needed at the end of each case in those languages is provided automatically in Go. Another important difference is that Go’s switch cases need not be constants, and the values involved need not be integers.

Switch cases evaluate cases from top to bottom, stopping when a case succeeds.

Switch without a condition is the same as switch true.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import (
"fmt"
"runtime"
)

func main() {
fmt.Print("Go runs on")
switch os := runtime.GOOS; os {
case "darwin":
fmt.Println("OS X.")
case "linux":
fmt.Println("Linux.")
default:
fmt.Println("%s.\n", os)
}
}

// With no condition
func main() {
t := time.Now()
switch {
case t.Hour() < 12:
fmt.Println("Good morning")
case t.Hour() < 17:
fmt.Println("Good afternoon")
default:
fmt.Println("Good evening")
}
}

Defer

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

The deferred call’s arguments are evaluated immediately, but the function call is not executed until the surrounding function returns.

1
2
3
4
5
6
func main() {
defer fmt.Println("world")
fmt.Println("hello")
}
// hello
// world

Deferred function calls are pushed onto a stack. When a function returns, its deferred calls are executed in last-in-first-out order.

1
2
3
4
5
6
7
8
9
10
11
12
13
func main() {
fmt.Println("counting")
for i := 0; i < 10; i++ {
defer fmt.Println(i);
}
fmt.Println("done")
}

// counting
// done
// 10
// 9
// ...