Switch Statement in Go

👋 Hey there!
I'm a community-driven software engineer, and I absolutely love diving into the world of cloud-native development and exploring the endless possibilities of open-source technologies. 💻
My skill set revolves around Kubernetes, GoLang, Python, Docker, and other fascinating container technologies. 🚀 And hey, just to add to the mix, I'm also CKA certified! 🎓
But you know what? My journey doesn't stop at coding. I have a genuine passion for technical evangelism. 🎤 I've had the privilege to speak at world-renowned events, sharing my knowledge and insights with others. It's such an exhilarating experience! And when I'm not on stage, you can find me pouring my thoughts into engaging technical blogs. 📝
If you've made it this far and you're intrigued by what you've read, let's not leave it at that! Reach out, and let's connect. Who knows what exciting opportunities may be awaiting us? 😊
A switch statement is another way to write a sequence of if-else statements.
Go’s switch is like the one in C and C++ except that it only runs the selected case, not all the cases that follow we don’t need a break statement here.
switch expression {
case exp1:
//Executes if expression matches exp1
case exp2:
//Executes if expression matches exp2
default:
//Executes if expression does not matches with any case
}
Switch evaluation order
Switch cases evaluate cases from top to bottom and stop when a case succeeds.
In the below example, it checks case "Linux": if os matches Linux then stop at that case else goes to the next case.
package main
import (
"fmt"
"runtime"
)
func main() {
//Prints which OS you're using
switch os := runtime.GOOS; os {
case "linux":
fmt.Println("Linux.")
case "darwin":
fmt.Println("OS X.")
default:
fmt.Printf("%s.\n", os)
}
}
Run this code in Go Playground
Switch with NO condition
Switch with no condition is like switch true. It is useful for writing a long if-else-if ladder.
package main
import (
"fmt"
"time"
)
func main() {
t := time.Now()
switch {
case t.Hour() < 12:
fmt.Println("Good morning!")
case t.Hour() < 17:
fmt.Println("Good afternoon.")
default:
fmt.Println("Good evening.")
}
}
Run this code in Go Playground
Thank you for reading this blog, and please give your feedback in the comment section below.




