If Control Statements
Key observations:
- Parentheses around conditional expressions are optional and conventionally omitted
- A short variable declaration can precede the condition, separated by a semicolon; variables declared this way are scoped to the entire if-else chain
- Prefer concise conditional expressions
- Go lacks a ternary conditional operator (e.g.,
a > b ? 1 : 0)
package main
import "fmt"
func main() {
threshold := 12
if score := 12; score < threshold {
fmt.Println("score below threshold")
} else if score == threshold {
fmt.Println("score matches threshold")
} else {
fmt.Println("score exceeds threshold")
}
}
Switch Control Statements
fallthrough forces execution to continue into the immediately following case block, skipping its condition check. It does not cascade through all subsequent cases.
package main
import "fmt"
func main() {
switch response := 'Y'; response {
case 'y', 'Y':
fmt.Println("affirmative")
fallthrough
case 'n', 'N':
fmt.Println("binary choice processed")
case 'a', 'A':
fmt.Println("all selected")
}
}
Output:
affirmative
binary choice processed
The default case can appear anywhere in the switch block; placement does not alter execution order.
switch token := 'z'; token {
default:
fmt.Println("unrecognized token")
case 'y', 'Y':
fmt.Println("affirmative")
fallthrough
case 'n', 'N':
fmt.Println("binary choice processed")
}
Output:
unrecognized token
To Loop Control Structures
Go provides only one loop construct: for, which supports multiple iteration patterns.
Range-Based Iteration Over Arrays
func iterateFixedArray() {
numbers := [5]int{7, 14, 21, 28, 35}
for index := range numbers {
fmt.Println(numbers[index])
}
}
Range-Based Iteration Over Slices
func iterateSubslice() {
base := [...]int{9, 18, 27, 36, 45, 54}
selected := base[3:]
for _, val := range selected {
fmt.Println(val)
}
}
func iterateMakeSlice() {
scores := make([]int, 4)
scores[0] = 89
scores[1] = 92
scores[3] = 77
for idx, s := range scores {
fmt.Printf("Position %d: %d\n", idx, s)
}
}
Output for iterateMakeSlice():
Position 0: 89
Position 1: 92
Position 2: 0
Position 3: 77
Range-Based Iteration Over Maps
func iterateStudentScores() {
gradeBook := map[string]int{"Charlie": 85, "Diana": 91, "Evan": 78}
// Iterate over keys only
for name := range gradeBook {
fmt.Println(name)
}
// Iterate over values only
for _, score := range gradeBook {
fmt.Println(score)
}
// Iterate over key-value pairs
for n, s := range gradeBook {
fmt.Printf("%s: %d\n", n, s)
}
}