Table of Contents | |
Understanding Go Switch
Statement
Go switch statement provides a way to handle multiple condition checks instead of writing a long chain of if-else if-else statements. You can use a switch
statement. This makes your code cleaner and easier to read. Switch evaluates an expression. Then compares it against a list of possible matches. It executes the block for the first matching case.
Syntax of Go switch
switch expression {
case value1:
// Code
case value2:
// Code
default:
// Code
}
Explanation
switch
keyword starts statement.expression
is what gets evaluated.case value1:
andcase value2:
check for matches.default:
runs if no other matches.
Example of Go switch
package main
import "fmt"
func main() {
day := 3
switch day {
case 1:
fmt.Println("Monday")
case 2:
fmt.Println("Tuesday")
case 3:
fmt.Println("Wednesday")
default:
fmt.Println("Other day")
}
}
Explanation
day := 3
assigns a value today
.switch day { ... }
checks the value ofday
.case 1:
,case 2:
,case 3:
represent options.fmt.Println("Wednesday")
executes.default:
handles unmatched cases.
Output
Wednesday
Go switch
Statement fallthrough
In a switch
statement, execution typically stops after finding the first matching case
. However, you can use the fallthrough
keyword to force execution to continue to the next case
. Even if that next case doesn’t match the original expression, use fallthrough
carefully, as it can lead to unexpected behavior if misused.
Syntax
switch expression {
case value1:
// Code
fallthrough
case value2:
// Code
}
Explanation
fallthrough
keyword is placed at the end.- Execution continues to the next
case
block. - No additional condition check is performed.
Example
package main
import "fmt"
func main() {
value := 1
switch value {
case 1:
fmt.Println("One")
fallthrough
case 2:
fmt.Println("Two")
default:
fmt.Println("Other")
}
}
Explanation
value := 1
assigns 1 to the variablevalue
.switch value { ... }
checks value.case 1:
matches and prints “One”.fallthrough
forces execution to nextcase
.case 2:
executes, and “Two”.default
will not be executed.
Output
One
Two
Go switch
Statement Multiple Cases
You can specify multiple values in a single case
statement within a switch
. Separate the values with commas. The corresponding code block will be executed if the switch expression matches any of these values. This simplifies the handling of several related conditions.
Syntax
switch expression {
case value1, value2, value3:
// Code
}
Explanation
case value1, value2, value3:
singlecase
.- If
expression
matches any, block executes. - Simplifies handling of related values.
Example
package main
import "fmt"
func main() {
char := "i"
switch char {
case "a", "e", "i", "o", "u":
fmt.Println("Vowel")
default:
fmt.Println("Consonant")
}
}
Explanation
char := "i"
assigns a character.switch char { ... }
checkschar
‘s value.case "a", "e", "i", "o", "u":
checks vowels.- If matches
fmt.Println("Vowel")
executes. default:
handles non-vowel characters.
Output
Vowel
Switch with Multiple Expressions in Case
Multiple expressions cannot be added to the switch
statement. However, you can group them into cases.
Syntax
switch expression {
case value1, value2:
// Code
case value3, value4:
// Code
}
Explanation
case value1, value2:
contains multiple values.case value3, value4:
contains multiple values.- If match found, related block will be executed.
Example
package main
import "fmt"
func main(){
num := 2
switch num{
case 1, 3, 5, 7, 9:
fmt.Println("Odd Number")
case 2, 4, 6, 8, 10:
fmt.Println("Even Number")
}
}
Explanation
num := 2
will assign value tonum
.switch num{ ... }
will be executed.- In
case 2, 4, 6, 8, 10:
match is found. fmt.Println("Even Number")
will be printed.
Output
Even Number
Switch without Expression
Go switch statement can be written without an explicit expression. In this case, it’s equivalent to switch
true
. Each case
statement then acts like an if condition. This form is useful for writing long if-else if-else chains more compactly.
Syntax
switch {
case condition1:
// Code
case condition2:
// Code
}
Explanation
- No explicit expression after
switch
. - Each
case
has a boolean condition. - First
case
withtrue
condition executes.
Example
package main
import "fmt"
func main() {
score := 85
switch {
case score >= 90:
fmt.Println("A")
case score >= 80:
fmt.Println("B")
case score >= 70:
fmt.Println("C")
default:
fmt.Println("D")
}
}
Explanation
score := 85
assigns a value.switch { ... }
has no expression.case score >= 90:
,case score >= 80:
, etc checks.- First true
case
executes. fmt.Println("B")
will be printed.
Output
B
Go switch
Optional Statement
In a Go switch statement, you can include an optional statement executed before the switch expression is evaluated. This is often used to declare variables scoped only to the switch
block. This keeps your code clean. It also limits the scope of variables.
Syntax
switch statement; expression {
case value1:
// Code
}
Explanation
statement;
is executed beforeexpression
.- Often used for variable declaration.
- Variables scoped to the
switch
block.
Example
package main
import "fmt"
func main() {
switch x := 10; x {
case 5:
fmt.Println("Five")
case 10:
fmt.Println("Ten")
default:
fmt.Println("Other")
}
}
Explanation
switch x := 10; x { ... }
declares and checks.x := 10
initializesx
within theswitch
.case 5:
,case 10:
are the cases.fmt.Println("Ten")
prints as case matches.
Output
Ten
Go switch
Statement break
In the switch
statement, the break
statement is generally unnecessary at the end of each case
block. Go automatically breaks out of the switch after a matching case
is executed. An explicit break is rarely used, except when exiting early from within a case. It could be before processing all.
Syntax
switch expression {
case value1:
// Code
if condition {
break // Optional break
}
// More code
}
Explanation
break
exits theswitch
statement.- Used within a
case
for early exit. - Go automatically breaks after each case normally.
Example
package main
import "fmt"
func main() {
num := 2
switch num {
case 1:
fmt.Println("One")
case 2:
fmt.Println("Two")
if true{
break
}
fmt.Println("After Break")
case 3:
fmt.Println("Three")
}
}
Explanation
num := 2
, intialized variable.switch num { ... }
switch case started.if true{ break }
will be executed.fmt.Println("After Break")
will not be executed.
Output
Two
Go switch
Statement default
The default
case in a switch
statement is optional. It’s executed if none of the other case
expressions match the switch
expression. The default
case can appear anywhere within the switch
block. It’s good practice to include it.
Syntax
switch expression {
case value1:
// Code
default:
// Code executed if no other case matches
}
Explanation
default:
is optional catch-all case.- Executes if no other
case
matches. - Can appear anywhere in the
switch
block.
Example
package main
import "fmt"
func main() {
number := 5
switch number {
case 1:
fmt.Println("One")
case 2:
fmt.Println("Two")
default:
fmt.Println("Neither One nor Two")
}
}
Explanation
number := 5
is assigned to variable.switch number { ... }
evaluatesnumber
.case 1:
andcase 2:
check for specific.default:
executes if no other case matches.fmt.Println("Neither One nor Two")
executes.
Output
Neither One nor Two
Checking DataTypes with switch
Statement
A type switch in Go is a special form of the switch
statement. It checks the type of an interface value rather than its value. You use the .(type) syntax to access the underlying type of an interface. This allows you to handle different types.
Syntax
switch variable.(type) {
case type1:
// Code
case type2:
// Code
default:
// Code
}
Explanation
variable.(type)
checks the type ofvariable
.case type1:
,case type2:
check specific types.default:
handles unknown types.
Example
package main
import "fmt"
func checkType(i interface{}) {
switch i.(type) {
case int:
fmt.Println("Integer")
case string:
fmt.Println("String")
default:
fmt.Println("Unknown type")
}
}
func main() {
checkType(10)
checkType("Hello")
checkType(true)
}
Explanation
func checkType(i interface{}) { ... }
accepts.switch i.(type) { ... }
is a type switch.case int:
,case string:
check types.checkType(10)
,checkType("Hello")
andcheckType(true)
calls function.
Output
Integer
String
Unknown type
Short Statement Before switch: Initializing Variables
Go allows you to include a short statement, typically a variable declaration, before the switch
expression. This variable is then available within the scope of the switch
statement, including all case
blocks. It’s a good way to declare and initialize.
Syntax
switch statement; expression {
case value1:
// Code
}
Explanation
statement;
executes beforeexpression
.- Often used for concise variable declaration.
- Variable’s scope is the entire
switch
block.
Example
package main
import "fmt"
import "math/rand"
func main() {
switch num := rand.Intn(10); num {
case 0:
fmt.Println("Zero")
case 1, 2, 3:
fmt.Println("Small")
default:
fmt.Println("Large")
}
}
Explanation
import "math/rand"
package imported.switch num := rand.Intn(10); num { ... }
declares.num
is scoped to theswitch
statement.case 0:
,case 1, 2, 3:
,default:
handle.
Output
Large
Note: The output can be Zero
, Small
, Large
because of rand.Intn(10)
will produce any number between 0-9
.
Conclusion
Go switch statement is a powerful construct for controlling program flow. It provides a cleaner alternative to long if-else chains. Understanding different forms of switch, including expressionless, type switches, and fallthrough. It helps you to write efficient and readable code. Experimenting with switch
will improve your Go programming skills. What creative uses of switch
can you use in your projects?