Lesson 5 of 60 · Go
Control Flow: if, switch, for Loops
Duration: 20 minutes
Control Flow: if, switch, for Loops
Control flow lets your program make decisions and repeat actions. Go keeps these constructs readable and consistent.
if statement
Use if to run code conditionally.
if n%2 == 0 {
fmt.Println("even")
} else {
fmt.Println("odd")
}
switch
Use switch when you want to compare one value against several possibilities.
switch day {
case "Mon", "Tue", "Wed", "Thu", "Fri":
fmt.Println("weekday")
case "Sat", "Sun":
fmt.Println("weekend")
default:
fmt.Println("unknown day")
}
switch does not fall through by default; this prevents bugs from missing break statements.
for loops
Go has one loop statement, for. It can act like a counter loop, a while loop, or an infinite loop.
for i := 0; i < 10; i++ {
fmt.Println(i)
}
j := 0
for j < 5 {
fmt.Println(j)
j++
}
for {
fmt.Println("running")
break
}