Lesson 4: Control Flow¶
Big Picture¶
flowchart TD
CF["Control flow in Go"] --> IF["if / else if / else<br/>optional init: if x := f(), cond"]
CF --> SW["switch<br/>no fallthrough by default<br/>multiple values per case"]
CF --> FOR["for — the ONLY loop"]
FOR --> F1["classic: for i:=0 → i<10 → i++"]
FOR --> F2["while-style: for cond"]
FOR --> F3["infinite: for {}"]
FOR --> F4["range: for i, v := range col"]
IF --> BC["break / continue"]
FOR --> BC
SW --> BC
Coming from Java/C? There is no while or do-while — for covers every looping need.
Concepts¶
If-Else¶
if condition {
// code
} else if anotherCondition {
// code
} else {
// code
}
// With initialization
if x := getValue(); x > 10 {
// x is scoped to this if block
}
Switch¶
For Loops¶
// Traditional
for i := 0; i < 10; i++ { }
// While-style
for condition { }
// Infinite
for { break }
// Range
for index, value := range collection { }
Code Walkthrough¶
package main
import "fmt"
func main() {
if n := 7; n%2 == 0 {
fmt.Println("even")
} else {
fmt.Println("odd") // prints
}
for i := 0; i < 3; i++ { fmt.Println(i) }
for _, v := range []string{"a", "b"} { fmt.Println(v) }
switch day := "Mon"; day {
case "Sat", "Sun":
fmt.Println("weekend")
default:
fmt.Println("weekday")
}
}
Full program: code/04_controlflow.go.
Exercises
- Write a
switchwith no condition (switch-true) to replace an if/else chain. - Use
for rangeon a string — what do you get for index and value? - Write a loop that skips even numbers using
continue.
Check Your Understanding¶
#
Does Go switch fall through to the next case by default?
#
Which loop keywords exist in Go? (select all that are real Go syntax)