Control Flow: switch (Multi-Way Branching & Type Switch) - Go Tutorial for Beginners #7
Video: Control Flow: switch (Multi-Way Branching & Type Switch) - Go Tutorial for Beginners #7 by Taught by Celeste AI - AI Coding Coach
Watch full page →Control Flow: switch (Multi-Way Branching & Type Switch) in Go
Switch statements in Go provide a clean and concise way to perform multi-way branching without needing explicit breaks. This tutorial covers basic switch usage, handling multiple values in cases, expressionless switches that behave like if-else chains, the fallthrough keyword, and type switches for interface types.
Code
package main
import (
"fmt"
)
func main() {
// Basic switch statement
day := "Tuesday"
switch day {
case "Monday":
fmt.Println("Start of the work week")
case "Tuesday", "Wednesday", "Thursday":
fmt.Println("Midweek days")
case "Friday":
fmt.Println("Almost weekend")
default:
fmt.Println("Weekend!")
}
// Expressionless switch (like if-else)
num := 7
switch {
case num < 0:
fmt.Println("Negative number")
case num == 0:
fmt.Println("Zero")
case num > 0:
fmt.Println("Positive number")
}
// Using fallthrough to continue to next case
grade := 'B'
switch grade {
case 'A':
fmt.Println("Excellent")
case 'B':
fmt.Println("Good")
fallthrough // continue to next case
case 'C':
fmt.Println("Average")
default:
fmt.Println("Needs Improvement")
}
// Type switch to determine the type of interface{}
var i interface{} = 42
switch v := i.(type) {
case int:
fmt.Printf("Integer: %d\n", v)
case string:
fmt.Printf("String: %s\n", v)
default:
fmt.Println("Unknown type")
}
}
Key Points
- Go's switch statements do not require explicit breaks; cases automatically break after execution.
- Multiple values can be handled in a single case by separating them with commas.
- Expressionless switches allow evaluating boolean expressions similar to if-else chains.
- The fallthrough keyword forces execution to continue to the next case regardless of matching.
- Type switches let you branch logic based on the dynamic type of an interface value.