Skip to content
Educora
Beginner14 min3 / 10

Conditions, loops and switch

Make decisions with `if` and its init statement, and learn every form of `for` — Go's only loop — and a `switch` that needs no `break`.

Check yourself
In this lesson you will learn
  • Write if, else if and if with an init statement
  • Use the classic, condition-only, infinite and range forms of for
  • Work with switch, fallthrough and labelled break

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.

Go
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)
	}
}
Expected output
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.

FormExampleIn other languages
Classicfor i := 0; i < 5; i++ { }for in C and Java
Condition onlyfor n < 100 { }while
Infinitefor { ... break }while (true)
With rangefor i, v := range items { }for-each
Over an integer (Go 1.22+)for i := range 5 { }range(5) in Python
Go
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))
	}
}
Expected output
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.

Go
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")
	}
}
Expected output
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.

A long if-else chain
if score >= 90 {
	grade = "A"
} else if score >= 75 {
	grade = "B"
} else if score >= 50 {
	grade = "C"
} else {
	grade = "F"
}
A switch with no expression
switch {
case score >= 90:
	grade = "A"
case score >= 75:
	grade = "B"
case score >= 50:
	grade = "C"
default:
	grade = "F"
}
Both versions do the same job, but with many conditions the switch reads more neatly. The cases are checked from top to bottom, and the first true condition wins.
Go
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")
}
Expected output
doing move
doing jump
finished
[]string{...} is a slice (list) of strings; you will study slices in a later lesson.

Key points

  • In if the condition has no parentheses but {} is required; an init statement (if x := f(); x > 0) limits the variable to the block.
  • for is Go's only loop: it has classic, condition-only, infinite and range forms.
  • range walks a string by characters and gives byte indexes; for i := range n works since Go 1.22.
  • switch needs no break; a case can list several values, and a switch with no expression replaces an if-else chain.
  • To stop the whole loop from a switch inside it, you need a labelled break.

Check yourself

10 questions. Every correct answer earns XP.

1 / 10
How do you write what other languages call a while loop in Go?