- Write
if,else ifandifwith an init statement - Use the classic, condition-only, infinite and
rangeforms offor - Work with
switch,fallthroughand labelledbreak
A weather app looks at the temperature and says “hot” or “cold”, and a game repeats the same steps until the player wins. To make decisions and repeat work, a program needs conditions and loops. Go has just three tools for this — if, for and switch — and each is as powerful as it is simple.
if, else and the init statement
In Go the condition is not put in parentheses, but curly braces are required even for a one-line block. With else if you can check as many conditions as you like. A special feature: before the condition you can write a short init statement followed by a semicolon, for example if n, err := strconv.Atoi(s); err == nil. Variables created there are visible only inside the if and else blocks.
package main
import (
"fmt"
"strconv"
)
func main() {
temperature := 28
if temperature > 30 {
fmt.Println("Hot")
} else if temperature > 20 {
fmt.Println("Warm")
} else {
fmt.Println("Cold")
}
if n, err := strconv.Atoi("17"); err == nil {
fmt.Println("double:", n*2)
}
if _, err := strconv.Atoi("abc"); err != nil {
fmt.Println("error:", err)
}
}Warm double: 34 error: strconv.Atoi: parsing "abc": invalid syntax
Conditions use comparison operators (==, !=, <, >, <=, >=) and logical operators: && (and), || (or), ! (not). In Go a condition must be a real bool: you cannot write if n as in C — you have to write if n != 0.
for — the only loop
Go has no while or do-while: every loop is written with for. But for comes in several forms and replaces all the loops of other languages. break stops the loop, and continue skips the rest of the current step and moves on to the next one.
| Form | Example | In other languages |
|---|---|---|
| Classic | for i := 0; i < 5; i++ { } | for in C and Java |
| Condition only | for n < 100 { } | while |
| Infinite | for { ... break } | while (true) |
| With range | for i, v := range items { } | for-each |
| Over an integer (Go 1.22+) | for i := range 5 { } | range(5) in Python |
package main
import "fmt"
func main() {
for i := 1; i <= 3; i++ {
fmt.Println("step", i)
}
n := 1
for n < 100 {
n *= 3
}
fmt.Println("n =", n)
for i := range 5 {
if i%2 == 0 {
continue
}
fmt.Println("odd:", i)
}
for i, r := range "Gəncə" {
fmt.Println(i, string(r))
}
}step 1 step 2 step 3 n = 243 odd: 1 odd: 3 0 G 1 ə 3 n 4 c 5 ə
The condition-only loop multiplies n by 3 until it passes 100: 1 → 3 → 9 → 27 → 81 → 243. Now look at the last loop: range walks over a string by characters (runes), not bytes, and i is the byte index where each character starts. Because ə takes two bytes, the index jumps from 1 straight to 3. If you don't need the index, write _ in its place: for _, r := range s.
switch
switch compares a value with several options. Unlike Java and C, Go does not need break at the end of each case: the matching block runs and the switch ends. One case can list several values separated by commas. A switch with no expression replaces a long if-else chain: each case holds its own condition.
package main
import "fmt"
func main() {
day := "Saturday"
switch day {
case "Saturday", "Sunday":
fmt.Println("Weekend")
default:
fmt.Println("Weekday")
}
score := 83
switch {
case score >= 90:
fmt.Println("Excellent")
case score >= 75:
fmt.Println("Good")
default:
fmt.Println("Keep going")
}
switch n := 2; n {
case 2:
fmt.Println("two")
fallthrough
case 3:
fmt.Println("three")
case 4:
fmt.Println("four")
}
}Weekend Good two three
Like if, switch accepts an init statement: switch n := 2; n. The fallthrough keyword also runs the next case block without checking its condition, which is why three was printed after two in the example. In real code it is rarely needed.
if score >= 90 {
grade = "A"
} else if score >= 75 {
grade = "B"
} else if score >= 50 {
grade = "C"
} else {
grade = "F"
}switch {
case score >= 90:
grade = "A"
case score >= 75:
grade = "B"
case score >= 50:
grade = "C"
default:
grade = "F"
}switch reads more neatly. The cases are checked from top to bottom, and the first true condition wins.package main
import "fmt"
func main() {
commands := []string{"move", "jump", "stop", "move"}
loop:
for _, c := range commands {
switch c {
case "stop":
break loop
default:
fmt.Println("doing", c)
}
}
fmt.Println("finished")
}doing move doing jump finished
[]string{...} is a slice (list) of strings; you will study slices in a later lesson.Key points
- In
ifthe condition has no parentheses but{}is required; an init statement (if x := f(); x > 0) limits the variable to the block. foris Go's only loop: it has classic, condition-only, infinite andrangeforms.rangewalks a string by characters and gives byte indexes;for i := range nworks since Go 1.22.switchneeds nobreak; acasecan list several values, and aswitchwith no expression replaces anif-elsechain.- To stop the whole loop from a
switchinside it, you need a labelledbreak.
Check yourself
10 questions. Every correct answer earns XP.
while loop in Go?