Control Flow
if and else in Go work as you'd expect, with one small difference from many other languages: the condition never needs parentheses, though the braces are always required, even for a single statement.
main.go
Try it yourself →package main
import "fmt"
func main() {
age := 20
if age >= 18 {
fmt.Println("You are an adult")
} else {
fmt.Println("You are a minor")
}
}Output
You are an adult
for is Go's only loop keyword
Go has no while or do-while — for covers every loop shape. With all three clauses, it's a classic counting loop; drop the init and post clauses and keep just a condition, and it behaves exactly like a while loop in any other language.
main.go
Try it yourself →package main
import "fmt"
func main() {
for i := 0; i < 3; i++ {
fmt.Println("counting up:", i)
}
n := 3
for n > 0 {
fmt.Println("counting down:", n)
n--
}
}Output
counting up: 0 counting up: 1 counting up: 2 counting down: 3 counting down: 2 counting down: 1
Next: arrays and slices — Go's fixed-size and growable collection types.
Practice exercise
Set a variable score := 73. Print "pass" if score is 60 or above, otherwise print "fail".