Control Flow
One loop keyword, a switch that does more, and if with a statement.
if
No parentheses around the condition, and braces are required:
package main
import "fmt"
func main() {
var n int = 10
if n > 5 {
fmt.Println("big")
} else if n > 2 {
fmt.Println("medium")
} else {
fmt.Println("small")
}
}if with a statement
An if can run a statement first, separated by a semicolon:
package main
import (
"fmt"
"strconv"
)
func main() {
if n, err := strconv.Atoi("42"); err == nil {
fmt.Println(n + 1)
}
}Referring to them afterwards does not compile:
package main
import (
"fmt"
"strconv"
)
func main() {
if n, err := strconv.Atoi("42"); err == nil {
fmt.Println(n)
}
fmt.Println(n)
}for is the only loop
Go has no while, no do, no foreach. The C-style form:
package main
import "fmt"
func main() {
for i := 0; i < 3; i++ {
fmt.Println(i)
}
}Drop the first and third parts and it is a while:
package main
import "fmt"
func main() {
n := 0
for n < 3 {
n++
}
fmt.Println(n)
}Drop the condition too and it runs forever, until something breaks out:
package main
import "fmt"
func main() {
count := 0
for {
count++
if count == 2 {
break
}
}
fmt.Println(count)
}range
range over an integer counts from zero. This form needs Go 1.22 — older code writes
for i := 0; i < 3; i++:
package main
import "fmt"
func main() {
for i := range 3 {
fmt.Println(i)
}
}Over a string it gives you the byte index and the character:
package main
import "fmt"
func main() {
for i, r := range "héllo" {
fmt.Println(i, string(r))
}
}switch
No parentheses, no break, and a case can list several values:
package main
import "fmt"
func main() {
day := "sat"
switch day {
case "sat", "sun":
fmt.Println("weekend")
case "mon":
fmt.Println("back to it")
default:
fmt.Println("weekday")
}
}fallthrough opts in, one case at a time:
package main
import "fmt"
func main() {
switch 1 {
case 1:
fmt.Println("one")
fallthrough
case 2:
fmt.Println("two as well")
}
}switch with no condition
Leave out the value and each case is a condition — switch { ... } is switch true.
This replaces an else if chain:
package main
import "fmt"
func main() {
score := 85
switch {
case score >= 90:
fmt.Println("A")
case score >= 80:
fmt.Println("B")
default:
fmt.Println("C")
}
}A switch takes a statement first too, like if:
package main
import "fmt"
func main() {
switch n := 2; n {
case 2:
fmt.Println("two")
}
}break and continue
A label lets you break or continue the outer loop:
package main
import "fmt"
func main() {
outer:
for i := range 3 {
for j := range 3 {
if j == 1 {
continue outer
}
if i == 2 {
break outer
}
fmt.Println(i, j)
}
}
}