3. Go Control Flow
Go's control flow statements are clean and straightforward. The language has if statements, switch statements, and three types of loops (for, while, and infinite loops). Go intentionally does not have a while or do-while statement; instead, you use for loops for all iteration needs. This simplicity makes Go code more readable and consistent.
Understanding control flow is essential for writing any nontrivial Go program. Go's control flow is designed to be simple, readable, and free of unnecessary syntax. The language's design philosophy emphasizes clarity and simplicity, making it easy to understand and maintain code.
If Statements
Go's if statements are similar to other languages but with some unique features like the ability to include a short variable declaration. The condition must be a boolean expression. Go does not require parentheses around the condition but does require curly braces around the body. The if statement can also include an else and else-if branches.
One of Go's unique features is the ability to include a short statement before the condition, which is scoped to the if block. This is useful for declaring variables that are only needed for the condition check. The short statement can be a variable declaration, assignment, or function call.
package main import ( "fmt" "strconv" ) func main() { score := 85 // Simple if statement if score >= 90 { fmt.Println("Grade: A") } // if-else if score >= 60 { fmt.Println("Pass") } else { fmt.Println("Fail") } // if-else if chain fmt.Println(" === Grade Calculation ===") if score >= 90 { fmt.Println("Grade: A (Excellent!)") } else if score >= 80 { fmt.Println("Grade: B (Good!)") } else if score >= 70 { fmt.Println("Grade: C (Satisfactory)") } else if score >= 60 { fmt.Println("Grade: D (Passing)") } else { fmt.Println("Grade: F (Fail)") } // if with short statement (variable scoped to if block) if x := 10; x > 5 { fmt.Println("x is greater than 5") } // fmt.Println(x) // This would be an error - x is not accessible here // if with short statement for error handling pattern value := "42" if num, err := strconv.Atoi(value); err == nil { fmt.Printf("Parsed number: %d ", num) } else { fmt.Printf("Error parsing: %v ", err) } // Nested if statements age := 20 hasID := true fmt.Println(" === Nested if ===") if age >= 18 { fmt.Println("Age verification passed.") if hasID { fmt.Println("License verified. Access granted.") } else { fmt.Println("License required. Access denied.") } } else { fmt.Println("Underage. Access denied.") } // Complex conditions with logical operators temperature := 75 isRaining := false fmt.Println(" === Complex Conditions ===") if temperature > 70 && temperature < 85 && !isRaining { fmt.Println("Perfect weather for a picnic!") } else if temperature > 85 || isRaining { fmt.Println("Not ideal weather. Stay inside.") } else { fmt.Println("Weather is okay.") } return }
Go's if with short statement is a powerful feature that scopes variables to the if block. The error handling pattern using if with short statement is common in Go: if err := doSomething(); err != nil { return err }. The logical operators && (AND), || (OR), and ! (NOT) work as expected with short-circuit evaluation.
Switch Statements
Go's switch statements are more powerful than in many other languages. They don't require break statements and can match on any type. Switch statements in Go do not fall through automatically; you must explicitly use the fallthrough keyword. This eliminates a common source of bugs found in other languages.
Switch statements can be used with expressions or without them (acting as a cleaner if-else chain). They can also be used with type assertions to match on the underlying type of an interface. The default case handles values not matched by other cases.
package main import ( "fmt" "time" ) func main() { // Basic switch day := 3 fmt.Println("=== Basic Switch ===") switch day { case 1: fmt.Println("Monday") case 2: fmt.Println("Tuesday") case 3: fmt.Println("Wednesday") case 4: fmt.Println("Thursday") case 5: fmt.Println("Friday") case 6: fmt.Println("Saturday") case 7: fmt.Println("Sunday") default: fmt.Println("Invalid day") } // Switch with multiple cases value := 5 fmt.Println(" === Switch with Multiple Cases ===") switch value { case 1, 3, 5, 7, 9: fmt.Printf("%d is odd ", value) case 2, 4, 6, 8, 10: fmt.Printf("%d is even ", value) default: fmt.Println("Other") } // Switch without expression (replaces if-else chains) score := 85 fmt.Println(" === Switch without Expression ===") switch { case score >= 90: fmt.Println("Grade: A") case score >= 80: fmt.Println("Grade: B") case score >= 70: fmt.Println("Grade: C") case score >= 60: fmt.Println("Grade: D") default: fmt.Println("Grade: F") } // Switch with short statement fmt.Println(" === Switch with Short Statement ===") switch x := 10; { case x > 10: fmt.Println("x > 10") case x == 10: fmt.Println("x == 10") default: fmt.Println("x < 10") } // Type switch fmt.Println(" === Type Switch ===") var data interface{} = "hello" switch v := data.(type) { case int: fmt.Printf("Integer: %d ", v) case string: fmt.Printf("String: %s ", v) case bool: fmt.Printf("Boolean: %t ", v) default: fmt.Printf("Unknown type: %T ", v) } // Fallthrough (rarely used) fmt.Println(" === Fallthrough ===") switch 2 { case 1: fmt.Println("One") fallthrough case 2: fmt.Println("Two") fallthrough case 3: fmt.Println("Three") } // Time-based switch fmt.Println(" === Time-based Switch ===") now := time.Now() switch now.Weekday() { case time.Saturday, time.Sunday: fmt.Println("It's the weekend!") default: fmt.Println("It's a weekday") } return }
Go's switch without expression acts as a cleaner if-else chain. The type switch allows matching on the underlying type of an interface. The fallthrough keyword is rarely used but available for explicit fall-through behavior. The default case handles values not matched by other cases.
For Loops
Go only has the for loop, but it can be used in different ways to serve all looping needs. The for loop can be used as a traditional for loop (with initialization, condition, and increment), as a while loop (with only a condition), or as an infinite loop (with no condition). The range keyword provides a convenient way to iterate over slices, arrays, maps, and strings.
Go's for loop is flexible and powerful. The break statement exits the loop entirely, while continue skips the rest of the current iteration. Labels can be used with break and continue to control nested loops. The range form is the most common way to iterate over collections.
package main import "fmt" func main() { // Standard for loop (like C) fmt.Print("Standard for: ") for i := 0; i < 5; i++ { fmt.Printf("%d ", i) } fmt.Println() // While loop (for without initialization/increment) fmt.Print("While style: ") j := 0 for j < 5 { fmt.Printf("%d ", j) j++ } fmt.Println() // Infinite loop (for without condition) fmt.Print("Infinite loop: ") k := 0 for { fmt.Printf("%d ", k) k++ if k >= 5 { break } } fmt.Println() // Range loop for slices numbers := []int{10, 20, 30, 40, 50} fmt.Print("Range over slice: ") for i, val := range numbers { fmt.Printf("numbers[%d]=%d ", i, val) } fmt.Println() // Range with only value (ignore index) fmt.Print("Only values: ") for _, val := range numbers { fmt.Printf("%d ", val) } fmt.Println() // Range over map ages := map[string]int{ "Alice": 30, "Bob": 25, "Charlie": 35, } fmt.Println("Range over map:") for name, age := range ages { fmt.Printf(" %s: %d ", name, age) } // Range over string (iterates over Unicode code points) text := "Hello 世界" fmt.Print("Range over string: ") for i, r := range text { fmt.Printf("%d:%c ", i, r) } fmt.Println() // Break and continue fmt.Print("Break and continue: ") for i := 0; i < 10; i++ { if i == 3 { continue // Skip 3 } if i == 7 { break // Exit at 7 } fmt.Printf("%d ", i) } fmt.Println() // Nested loops with labels fmt.Println("Nested loops:") outer: for i := 0; i < 3; i++ { for j := 0; j < 3; j++ { if i == 1 && j == 1 { fmt.Println("Breaking outer loop at (1,1)") break outer } fmt.Printf("(%d,%d) ", i, j) } } fmt.Println() return }
The range keyword simplifies iteration over slices, maps, and strings. break and continue provide fine-grained control over loop execution. Labels allow breaking or continuing nested loops from an outer scope. The infinite loop pattern (for { ... }) is common for server applications.
Knowledge Check
Ready to test your understanding of 3. Go Control Flow?