Variables and control flow
Declare variables, read zero values, and branch with if, switch and the single for loop.
- Choose := inside functions and var when you want an explicit declaration.
- Remember that every type has a zero value before assignment.
- Use if/else for two paths and switch for many named cases.
- Use for for counting, ranging and condition loops.
In plain English
A variable holds a value, and Go lets you declare one with var for an explicit statement or with := for a short inferred declaration inside a function. A zero value is the automatic default a variable gets before you assign to it, like 0 for numbers, false for booleans and "" for strings. if/else runs one block or the other based on a condition, and switch chooses between several named cases without needing a break. Go has one loop, for, which covers counting, ranging over values and looping while a condition holds.
Step by step
- 1Declare a variable with var or := depending on how much you want to spell out.
- 2Read the zero value your variable starts with before assigning.
- 3Branch with if/else when there are two outcomes.
- 4Choose between many named cases with switch.
- 5Loop with for for counting, ranging and conditions.
package main
import "fmt"
var maxLessons = 14
func main() {
var minutes int
var published bool
fmt.Println(minutes, published)
minutes = 12
published = true
title := "Variables and control flow"
if published && minutes >= maxLessons {
fmt.Println(title, "is long")
} else {
fmt.Println(title, "is short")
}
switch minutes {
case 5:
fmt.Println("quick")
case 12:
fmt.Println("steady")
default:
fmt.Println("other")
}
for i := 1; i <= 3; i++ {
fmt.Println("lesson", i)
}
}Common mistakes
- Declaring a variable with := at package scope fails, because := is only allowed inside functions.
- Forgetting that a fresh variable starts at its zero value can hide bugs when you assume it is already set.
- Writing a while loop with while does not work in Go, because for is the only loop keyword.
- Assuming switch needs a break after each case is wrong; Go cases do not fall through by default.
Classify a lesson length
Write a function classify(minutes int) string that returns "short" when minutes is under 10 and "long" otherwise.
func classify(minutes int) string {
return ""
}What value does a declared but unassigned int have in Go?
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Lock in what you just learned.
Mark this lesson complete to save your place and move one step closer to the certificate.