Golang switch/case keywords
last modified May 7, 2025
This tutorial explains how to use the switch
and case
keywords in Go. We'll cover conditional logic basics with practical examples of
switch/case statements.
The switch/case construct provides multi-way branching based on the
value of an expression. It uses switch
to define the control flow
and case
to specify conditions. It's cleaner than multiple if-else
statements for many scenarios.
In Go, switch
and case
support various forms:
expression switches, type switches, and fallthrough for specialized control
flow. Together, they form a versatile tool for decision-making.
Basic switch/case statement
The simplest form uses switch
to evaluate an expression and
case
to match specific values. This example demonstrates basic
switch/case usage with numbers.
package main import "fmt" func main() { num := 3 switch num { case 1: fmt.Println("One") case 2: fmt.Println("Two") case 3: fmt.Println("Three") default: fmt.Println("Unknown number") } }
The switch
evaluates num
, and each case
checks for a match. The default
case runs if no case
matches. In Go, case
clauses automatically break, eliminating the
need for explicit break
statements.
Switch/case with expressions
Go allows expressions in case
clauses, enabling complex conditions.
This example shows how to use comparisons in switch/case.
package main import "fmt" func main() { score := 85 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") } }
Without an expression after switch
, the case
clauses
act like an if-else chain. Each case
evaluates a condition, and the
first true case
executes. This approach enhances readability.
Switch/case with multiple values
A single case
can test multiple comma-separated values. This
example checks for vowels using switch/case.
package main import "fmt" func main() { char := 'e' switch char { case 'a', 'e', 'i', 'o', 'u': fmt.Printf("%c is a vowel\n", char) case 'y': fmt.Printf("%c is sometimes a vowel\n", char) default: fmt.Printf("%c is a consonant\n", char) } }
The case
with multiple values matches any listed vowel. This makes
the code concise and clear. The switch
here works with runes
(characters).
Fallthrough in switch/case
Go's fallthrough
keyword, used within a case
,
transfers control to the next case
. This example demonstrates its
behavior.
package main import "fmt" func main() { num := 2 switch num { case 1: fmt.Println("One") case 2: fmt.Println("Two") fallthrough case 3: fmt.Println("Three") case 4: fmt.Println("Four") default: fmt.Println("Unknown") } }
When num
is 2, the case
prints "Two" and uses
fallthrough
to execute the next case
, printing
"Three". Unlike many languages, Go requires explicit fallthrough
to
continue to the next case
.
Type switch with case
Go's type switch uses switch
and case
to check the
type of an interface variable. This example identifies different types.
package main import "fmt" func checkType(x interface{}) { switch x.(type) { case int: fmt.Println("Integer") case float64: fmt.Println("Float64") case string: fmt.Println("String") case bool: fmt.Println("Boolean") default: fmt.Println("Unknown type") } } func main() { checkType(42) checkType(3.14) checkType("hello") checkType(true) }
The switch x.(type)
syntax pairs with case
clauses to
match specific types. This is useful for dynamic type handling in Go.
Switch/case with initialization
A switch
statement can include an initialization clause, and
case
clauses define the conditions. This example demonstrates this
feature.
package main import ( "fmt" "time" ) func main() { switch hour := time.Now().Hour(); { case hour < 12: fmt.Println("Good morning!") case hour < 17: fmt.Println("Good afternoon!") default: fmt.Println("Good evening!") } }
The switch
initializes the hour
variable, scoped to
the block, and each case
evaluates a condition. This keeps related
logic compact.
Practical example: Command processor
This example uses switch
and case
to build a command
processor, showing real-world application.
package main import ( "fmt" "strings" ) func processCommand(cmd string) { switch strings.ToLower(cmd) { case "start": fmt.Println("Starting system...") case "stop": fmt.Println("Stopping system...") case "status": fmt.Println("System is running") case "help", "?": fmt.Println("Available commands: start, stop, status, help") default: fmt.Println("Unknown command") } } func main() { processCommand("start") processCommand("HELP") processCommand("invalid") }
The switch
processes a command, and each case
handles
a specific command. Multiple values in a case
(e.g., "help", "?")
map to the same action. The default
case handles invalid input.
Source
This tutorial covered the switch
and case
keywords in
Go, demonstrating their use in various conditional logic scenarios.
Author
List all Golang tutorials.