Switch Case statements are an efficient alternative to if…else construct. Both the constructs i.e. if…else & switch case are similar and used to select & execute one of many available code blocks based on certain conditions. So, when to use switch case?
When the number of alternatives/options are high (say more than 4) an if else looks cluttered where as a switch case looks tidy, readable and to some extent performs better than if…else construct.
The following code sample will familiarize you with switch case syntax. Note: For this example if…else construct would have been equally good.
The example shows you a for loop to get integers starting from 1 to 20. The logic in the for loop checks each number from 1 to 20 using remainder operator. If the remainder is 0 after division with 2 we are printing is Even otherwise it’ll print is Odd.
package main import "fmt" func main(){ for i := 1; i< 21; i++ { var j int j = i%2 switch j { case 0: fmt.Println(i, "is Even") default: fmt.Println(i, "is Odd") } } }
Output of the above code sample:
fallthrough in switch case statement
When fallthrough keyword is used inside a switch case statement, the control automatically moves and execute the next code block. An example code with output is shown below for your reference.
package main import "fmt" func main(){ fmt.Println("Select your lucky workingday [Mon, Tue....Fri]") fmt.Println("Note: Entries are case sensitive") var s string fmt.Scanf("%s", &s) switch s { case "Mon": fmt.Println("I don't like Monday") case "Tue": fmt.Println("Hmmm Tuesday...OK") case "Wed": fmt.Println("Wednesday. Hmmm mid-week") case "Thu": fmt.Println(":) 1 more day to go for Friday") case "Fri": fmt.Println("TGIF") fallthrough default: fmt.Println("Entry not valid OR result of a fallthrough") } }
Output
The output is the reflection of a typical switch case behavior as expected. Just concentrate on the section where you’ve given the input as “Fri”. What happens here?
The output executes the matching statement based on the input and then the control also goes to the next statement because of the fallthrough effect.
Share it if you like it.
Basant Singh
Latest posts by Basant Singh (see all)
- Go Maps Introduction for Beginners - May 20, 2015
- Go Programming – Arrays and Slices - May 11, 2015
- Golang Switch Case with Sample Code - May 1, 2015