GoLang 101 — (20) Understanding The Switch Statements in Go
Yeah, Day 21
The switch
statement is a condition to make decisions based on the value of an expression. The default syntax for this switch
statements will looks like this.
switch expression {
case exp1:
// code for exp1
case exp2:
// code for exp2
// ...
default:
// code for other cases
}
The expression
is evaluated, and the matching case
block is executed. We can have multiple case
values for a single case
block. The default
block is optional and runs when none of the case
values match.
Single-Case Example
Okay, let’s generate single-case example, we generate a very basic calculator quizzes.
package main
import (
"fmt"
)
func main() {
var answers int
fmt.Println("Guess: 50+54")
fmt.Println("Your answer:")
fmt.Scanln(&answers)
switch answers {
case 104:
fmt.Println("Correct, Congrats")
default:
fmt.Println("Wrong")
}
}
Those program will give you question 50 + 54 and you have to guess it. If you guess it right, it will give you answer “Correct, Congrats”, instead you will get “Wrong”.
Multi-Case Example
For the multi-case, we can give more than one case in every statements. If any of the values match, the block will be executes. Let generate simple program to check the weathers.
package main
import (
"fmt"
)
func main() {
var month string
fmt.Print("Enter the name of the month: ")
fmt.Scanln(&month)
switch month {
case "January", "February", "December":
fmt.Println("It's winter")
case "March", "April", "May":
fmt.Println("It's spring")
case "June", "July", "August":
fmt.Println("It's summer")
case "September", "October", "November":
fmt.Println("It's autumn")
default:
fmt.Println("Invalid month!!!")
}
}
This program prompts the user to enter the name of a month. Based on the input, it uses a switch
statement to determine the season associated with that month. Each case represents a range of months corresponding to a particular season. If the entered month doesn't match any of the cases, the program prints "Invalid month!!!"
Looks at the output, I try to input january
instead of January
. You are correct, switch statements is case-sensitive. So, you need to be careful, especially when you build big apps with many cases on it.
Notes
For your note, there are two substance that not included in this article, the Switch statements have break
and fallthrough
. Actually it’s very simple concept. For break
every statements that passing this case will be stop. For fallthrough
every statements will be proceed to the next cases even if the current one matches.
Conclusions
Finally, we already come into the closing of this article. Switch statements is just the same with other conditional formatting. It may provide cleaner and more readable code, especially when dealing with multiple conditions. But, in complex situations, you probably choose the If-Else statements.
Thanks for reading 💎