Control Flow

View saved

If statements

Parentheses around conditions are optional; braces are required.

score := 82
if score >= 70 {
	fmt.Println("passed")
} else {
	fmt.Println("retry")
}

For loops

Go has one loop keyword. Use it as a C-style loop, a while-style loop, or an infinite loop with break.

for i := 1; i <= 3; i++ {
	fmt.Println(i)
}

n := 3
for n > 0 {
	fmt.Println(n)
	n--
}

Range over slices and maps

range yields index and value, or key and value.

colors := []string{"red", "green"}
for i, c := range colors {
	fmt.Println(i, c)
}

Switch

Cases do not fall through by default.

day := "sat"
switch day {
case "sat", "sun":
	fmt.Println("weekend")
default:
	fmt.Println("weekday")
}

Comments

One comment per signed-in account. Comments are saved with this page’s URL.