If / Else
Go's if statement doesn't require parentheses around the condition, but curly braces are mandatory:
age := 18
if age >= 18 {
fmt.Println("Adult")
} else if age >= 13 {
fmt.Println("Teenager")
} else {
fmt.Println("Child")
}
If with initialization statement
// v is scoped to the if/else block
if v := getValue(); v > 100 {
fmt.Println("Large:", v)
} else {
fmt.Println("Small:", v)
}
Switch statement
day := "Monday"
switch day {
case "Saturday", "Sunday":
fmt.Println("Weekend!")
case "Monday":
fmt.Println("Start of the week")
default:
fmt.Println("Weekday")
}
For loop — the only loop in Go
// Classic C-style for
for i := 0; i < 5; i++ {
fmt.Println(i)
}
// While-style (condition only)
n := 1
for n < 100 {
n *= 2
}
// Infinite loop
for {
// break to exit
break
}
Range — iterate over collections
nums := []int{2, 3, 4}
for i, v := range nums {
fmt.Printf("index %d: value %d
", i, v)
}
// Ignore index with _
for _, v := range nums {
fmt.Println(v)
}