Control Flow
For the most part, control flow keywords in Go do not require parenthesis ()
for the conditional statements but do require brackets {}
to contain the logic.
For loops
For loops in Go are similar to C++ in that they have an inital, conditional, and post statement in the declaration. Initial and post statements are optional if not needed. In that case, this becomes Go's while
loop. You can go even further by dropping the condition all together to create an forever loop.
package main
import "fmt"
func main() {
sum := 0
for i := 0; i < 10; i++ {
sum += i
}
fmt.Println(sum)
// While
sum = 1
for sum < 1000 {
sum += sum
}
fmt.Println(sum)
// Forever loop
for {
// repeats forever
}
}
You can use the range
keyword to iterate over a slice or map. With a slice, you will get both the index and a copy of the element for each iteration.
var pow = []int{1, 2, 4, 8, 16, 32, 64, 128}
for i, v := range pow { // i or v can be ignored with _
fmt.Printf("2**%d = %d\n", i, v)
}
If/Else
If statements in Go can also include short statements to execute before the condition, and variables in these statements are scoped to the if/else block.
func pow(x, n, lim float64) float64 {
if v := math.Pow(x, n); v < lim {
return v
}
else if v == lim {
fm.Printf("%g == %g\n", v, lim)
}
else {
fmt.Printf("%g >= %g\n", v, lim)
}
return lim
}
Switch
In Go, only the matching case is run, meaning you do not need to include break
like you would in C++. The switch case stops evaluating after one of the cases matches, so you can not run multiple cases even if it matches multiple. Switch can also be written with no condition, effectively turning it into a long if/else block.
import (
"fmt"
"runtime"
"time"
)
switch os := runtime.GOOS; os {
case "darwin":
fmt.Println("OS X.")
case "linux":
fmt.Println("Linux.")
default:
fmt.Printf("%s.\n", os)
}
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
Defer can be used to delay a function call until the surrounding function returns. Defers can be stacked, and will execute on a last-in, first-out order.
package main
import "fmt"
func main() {
defer fmt.Println("world")
fmt.Println("hello")
}