If, For Loops, and Multiple Return Values
Write if statements with short initialization, iterate with Go's single for loop, and return (value, error) pairs from functions. After this, you can write idiomatic Go control flow and multi-return helpers.
Course content
Sign in to save your progress.
-
Before You Write Code
-
Why Go Exists and When to Pick It
-
Run Your First Go Program
-
-
-
Values, Control Flow, and Functions
-
Variables, Types, and Zero Values
-
If, For Loops, and Multiple Return Values
-
-
-
Slices, Maps, and Structs
-
Arrays, Slices, and Why append Matters
-
Maps, Structs, and Pointer Receivers
-
-
-
Errors, Packages, and Testing
-
Handle Errors Without Hiding Them
-
Packages, Exports, and go test
-
-
-
Files, JSON, and a Small HTTP Server
-
Read Files and Decode JSON Structs
-
Build and Test a Small net/http Server
-
-
-
Pointers, Modules, and CLIs
-
Pointers and Memory Basics
-
Managing Dependencies and internal/ Packages
-
Building CLIs With flag, os.Getenv, and Exit Codes
-
-
Go strips control flow down to the bare minimum: there is no while keyword, no do-while, and no ternary cond ? a : b operator. Everything is expressed with if, switch, and for—paired with functions that return multiple values so error handling stays flat and readable.
Skip ahead
If you already use scoped if initializers, expressionless switch, all four for forms, and know why for _, item := range slice copies each element, take the section quiz or move on to "Arrays, Slices, and Why append Matters."
Experiment 1: Multiple return values and scoped if statements
In Go, functions that validate input or perform I/O return (result, error). Look at how if port, err := parsePort(s); err != nil keeps both port and err tightly scoped to the if/else block:
package main
import (
"fmt"
"strconv"
)
func parsePort(raw string) (int, error) {
p, err := strconv.Atoi(raw)
if err != nil {
return 0, fmt.Errorf("invalid port %q: %w", raw, err)
}
if p < 1 || p > 65535 {
return 0, fmt.Errorf("port %d out of range", p)
}
return p, nil
}
func main() {
for _, s := range []string{"8080", "abc", "70000"} {
if port, err := parsePort(s); err != nil {
fmt.Println("err:", err)
} else {
fmt.Println("ok:", port)
}
}
}
ok: 8080
err: invalid port "abc": strconv.Atoi: parsing "abc": invalid syntax
err: port 70000 out of range
Notice the early-return style inside parsePort: each invalid condition returns immediately so the happy path (return p, nil) sits cleanly at the left margin instead of buried three indentation levels deep.
Experiment 2: Clean branching with expressionless switch
Unlike C or JavaScript, Go's switch breaks automatically after each matching case—no accidental fall-through bugs. Even better, you can omit the value after switch to replace long if / else if / else chains cleanly:
func shippingFee(weightKg float64) int {
switch {
case weightKg <= 1:
return 50
case weightKg <= 5:
return 120
default:
return 250
}
}
func main() {
fmt.Println("fees:", shippingFee(0.5), shippingFee(3.2), shippingFee(9))
}
fees: 50 120 250
Experiment 3: Every loop is a for loop
Go replaces for, while, and foreach with four variations of for:
- Counted loop (Go 1.22+):
for i := range 3 { ... }runs withi = 0, 1, 2. - Collection loop:
for i, v := range items { ... }iterates slices, maps, strings, or channels. - While-style loop:
for retries < 3 { ... }repeats while a condition holds. - Infinite loop:
for { ... }loops until abreakorreturnexits (common in worker and server loops).
Experiment 4: The range copy trap when updating a slice
This bug catches almost every Go beginner at least once. Suppose you want to apply a 100-cent discount to every item in a shopping cart. Look at what happens when you modify the second variable from for _, it := range cart versus indexing cart[i]:
package main
import "fmt"
type Item struct {
Name string
Price int
}
func main() {
cart := []Item{{Name: "Keyboard", Price: 1200}, {Name: "Mouse", Price: 450}}
for _, it := range cart {
it.Price -= 100 // modifies a COPY only!
}
fmt.Println("after value range:", cart)
for i := range cart {
cart[i].Price -= 100 // modifies slice element in place
}
fmt.Println("after index range:", cart)
}
after value range: [{Keyboard 1200} {Mouse 450}]
after index range: [{Keyboard 1100} {Mouse 350}]
Why did the first loop leave both prices untouched? Because range copies each Item struct into the loop variable it on every iteration. Changing it.Price only changed that throwaway copy. When you need to mutate elements inside a slice, iterate by index (for i := range cart) and update cart[i] directly.
Common mistakes
- Mutating the copy in
for _, item := range items: Leaves the original slice unchanged. Useitems[i](or a slice of pointers[]*Item) when mutating. - Putting the opening brace
{on the next line: Go inserts automatic semicolons at line breaks, soif ok\n{is a syntax error. - Relying on map iteration order in
for k, v := range myMap: Go intentionally randomizes map iteration order on every run. Sort the keys withslices.Sorted(maps.Keys(myMap))when deterministic output matters.
💡 Tip
If you only need the index in a range loop, write for i := range cart—no need for for i, _ := range cart. And if you need neither index nor value (just repeating 5 times), write for range 5.
What happens if you skip this step
Mutating the value copy in a range loop compiles with zero warnings and silently drops your updates—often passing simple tests that forget to assert the modified slice afterward.
In a slice of structs orders := []Order{...}, why does for _, o := range orders { o.Status = "paid" } leave every order in orders unpaid, and how do you fix it in one line?
About
Write if statements with short initialization, iterate with Go's single for loop, and return (value, error) pairs from functions. After this, you can write idiomatic Go control flow and multi-return helpers.
- Duration
- 5 min
- Last update
- 11/27/2026
Comments
Sign in to commentNo comments yet.