Golang Switch Case Statement

Glitch
2 min readMar 17, 2023

--

Switch case is a control flow statement that allows developers to evaluate an expression and execute different blocks of code based on the value of that expression. It is a common construct in programming languages, including Golang. In this blog, we will discuss the switch case statement in Golang and how to use it effectively.

Syntax of switch case statement in Golang

The syntax for switch case statement in Golang is as follows:
switch expression {
case value1:
// code to execute if expression is equal to value1
case value2:
// code to execute if expression is equal to value2
case value3:
// code to execute if expression is equal to value3
default:
// code to execute if expression is not equal to any of the values above
}
In the switch case statement, the expression is evaluated, and the code inside the block corresponding to the matching case is executed. If none of the cases match, the default block is executed (if present).

Examples of switch case statement in Golang

Here are a few examples to demonstrate how to use the switch case statement in Golang:

Example 1:
package main

import "fmt"

func main() {
var grade string = "A"
switch grade {
case "A":
fmt.Println("Excellent!")
case "B", "C":
fmt.Println("Well done")
case "D":
fmt.Println("You passed")
case "F":
fmt.Println("Better try again")
default:
fmt.Println("Invalid grade")
}
}
In the above example, we are using the switch case statement to evaluate the value of the variable grade and execute different blocks of code based on its value. If grade is equal to "A", the message "Excellent!" is printed. If it is equal to "B" or "C", the message "Well done" is printed. If it is equal to "D", the message "You passed" is printed. If it is equal to "F", the message "Better try again" is printed. If the value of grade is none of the above, the message "Invalid grade" is printed.

Example 2:
package main

import "fmt"

func main() {
var num int = 15
switch {
case num%2 == 0:
fmt.Println(num, "is even")
case num%2 != 0:
fmt.Println(num, "is odd")
}
}
In the above example, we are using the switch case statement without an expression. Instead, we are evaluating the value of the variable num using conditions. If num is even, the message "num is even" is printed. If it is odd, the message "num is odd" is printed.

Conclusion

The switch case statement is a powerful construct in Golang that allows developers to evaluate expressions and execute different blocks of code based on their values. It is an essential tool for writing efficient and readable code. By using the examples discussed in this blog, you can learn how to use the switch case statement in your Golang programs effectively.

--

--

No responses yet