Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

GO
Go
0/12 completed
Beginner
Hello GoTypes and variablesControl flowFunctions
Intermediate
Arrays, slices and mapsStructs and methodsInterfacesError handling
Advanced
GenericsGoroutines and channels
Pro
Building an HTTP serverModules, testing and tooling
Tracks / Go / Beginner

Control flow

Go keeps control flow small: one loop keyword (for), if, switch and defer. There are no parentheses around conditions, and braces are always required. Less syntax means less to remember and code that looks the same everywhere.

if

go
package main

import "fmt"

func main() {
	temp := 31
	if temp > 30 {
		fmt.Println("hot")
	} else if temp > 20 {
		fmt.Println("warm")
	} else {
		fmt.Println("cold")
	}

	// if with a short statement: v only exists inside the if/else
	if v := temp * 9 / 5 + 32; v > 85 {
		fmt.Println(v, "°F is hot too")
	}
}
Output
hot
87 °F is hot too

The short statement form (if x := …; condition) is everywhere in Go, especially with errors:

go
package main

import (
	"fmt"
	"strconv"
)

func main() {
	for _, input := range []string{"42", "forty-two"} {
		if n, err := strconv.Atoi(input); err != nil {
			fmt.Println("bad input:", err)
		} else {
			fmt.Println("doubled:", n*2)
		}
	}
}
Output
doubled: 84
bad input: strconv.Atoi: parsing "forty-two": invalid syntax

Conditions must be real booleans: if count doesn't compile; write if count != 0. There's no ternary operator (a ? b : c) either. Use an if.

for: the only loop

for covers all the loop shapes other languages split into for, while and do:

go
package main

import "fmt"

func main() {
	// classic three-part loop
	for i := 0; i < 5; i++ {
		fmt.Print(i*i, " ")
	}
	fmt.Println()

	// "while" loop: only a condition
	n := 27
	steps := 0
	for n != 1 {
		if n%2 == 0 {
			n /= 2
		} else {
			n = 3*n + 1
		}
		steps++
	}
	fmt.Println("27 reaches 1 in", steps, "steps")

	// infinite loop with break
	tries := 0
	for {
		tries++
		if tries == 3 {
			break
		}
	}
	fmt.Println("stopped after", tries, "tries")

	// range over an integer (Go 1.22+)
	for i := range 3 {
		fmt.Print("round ", i, "; ")
	}
	fmt.Println()
}
Output
0 1 4 9 16
27 reaches 1 in 111 steps
stopped after 3 tries
round 0; round 1; round 2;

range over collections

go
package main

import "fmt"

func main() {
	fruits := []string{"apple", "banana", "cherry"}
	for i, f := range fruits {
		fmt.Println(i, f)
	}
	for _, f := range fruits {      // ignore the index with _
		fmt.Print(len(f), " ")
	}
	fmt.Println()

	ages := map[string]int{"Asha": 31, "Ravi": 28}
	for name, age := range ages {
		fmt.Println(name, "is", age)
	}
}
Output
0 apple
1 banana
2 cherry
5 6 6
Ravi is 28
Asha is 31

range works on slices, arrays, strings (by rune), maps, channels, integers and iterator functions. Over a map, the order is deliberately random on every run, so never rely on it. (Here there are only two entries; sort the keys first when order matters, as you'll see in the next lessons.)

break, continue and labels

go
package main

import "fmt"

func main() {
	for i := range 10 {
		if i%2 == 0 {
			continue
		}
		if i > 7 {
			break
		}
		fmt.Print(i, " ")
	}
	fmt.Println()

	// a label lets break leave an outer loop
	grid := [][]int{{1, 2, 3}, {4, -1, 6}, {7, 8, 9}}
outer:
	for r, row := range grid {
		for c, v := range row {
			if v < 0 {
				fmt.Printf("found negative at row %d, col %d\n", r, c)
				break outer
			}
		}
	}
}
Output
1 3 5 7
found negative at row 1, col 1

switch

Go's switch is cleaner than C's: cases don't fall through (no break needed), a case can list several values, and cases don't have to be constants:

go
package main

import (
	"fmt"
	"time"
)

func main() {
	for _, cmd := range []string{"start", "stop", "halt", "dance"} {
		switch cmd {
		case "start":
			fmt.Println("starting")
		case "stop", "halt":
			fmt.Println("stopping")
		default:
			fmt.Println("unknown command:", cmd)
		}
	}

	// switch with no value: a clean if/else chain
	score := 82
	switch {
	case score >= 90:
		fmt.Println("A")
	case score >= 75:
		fmt.Println("B")
	default:
		fmt.Println("C")
	}

	day := time.Date(2026, 11, 22, 0, 0, 0, 0, time.UTC).Weekday()
	switch day {
	case time.Saturday, time.Sunday:
		fmt.Println(day, "is the weekend")
	default:
		fmt.Println(day, "is a weekday")
	}
}
Output
starting
stopping
stopping
unknown command: dance
B
Sunday is the weekend

If you really want C-style fall-through, write fallthrough at the end of a case, but you'll rarely need it.

defer

defer schedules a function call to run when the surrounding function returns, however it returns. It's Go's way of making sure cleanup happens:

go
package main

import "fmt"

func process() {
	fmt.Println("open connection")
	defer fmt.Println("close connection")   // runs last

	for i := range 3 {
		defer fmt.Println("deferred", i)    // deferred calls run in reverse order
	}
	fmt.Println("working…")
}

func main() {
	process()
	fmt.Println("back in main")
}
Output
open connection
working…
deferred 2
deferred 1
deferred 0
close connection
back in main

Deferred calls run last-in, first-out, like a stack. The typical use: open a resource, and on the very next line defer closing it, so you can't forget:

go
f, err := os.Open("data.csv")
if err != nil {
	return err
}
defer f.Close()
// … use f; it's closed when the function returns, even on an early return

panic and recover

A panic is Go's crash: an unrecoverable error like an out-of-range index or a nil-pointer dereference. Deferred functions still run, and then the program exits with a stack trace:

go
package main

import "fmt"

func main() {
	defer fmt.Println("deferred calls still run")
	nums := []int{1, 2, 3}
	i := 5
	fmt.Println(nums[i])
}
Output
deferred calls still run
panic: runtime error: index out of range [5] with length 3

goroutine 1 [running]:
main.main()
	/work/main.go:9 +0x58
exit status 2

Panics are for bugs, not normal errors. Expected failures (missing file, bad input, network down) are returned as error values. A deferred recover() can stop a panic, and web servers use it so one bad request doesn't take down the whole server, but you'll rarely write it yourself.

Practice

  1. Print FizzBuzz for 1 to 30 with a for and a value-less switch.
  2. Loop over "Go is fun!" with range and count the vowels.
  3. Use a labelled break to stop searching a 2D slice as soon as you find a target value.
  4. Write a function that prints "start", defers "end", and returns early from the middle. Check that "end" still prints.
✎ Check your understanding

1.How do you write a "while" loop in Go?

2.Do Go switch cases fall through to the next case?

3.In what order do three deferred calls run?

4.What's the order of for k, v := range someMap?

← Types and variables