Skip to content

Go Programming

Golang Switch Case with Sample Code

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.

Play here with the below code

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:

EvenOddfallthrough 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.

OP-fallthrough

Play here

Share it if you like it.

Be Sociable, Share!
    The following two tabs change content below.

    Basant Singh

    Basant is a talented software developer who is very engaged in web & cloud platforms on a daily basis. He is a contributor to codingthis.com reporting on various news and troubleshooting on various platforms. Basant is very strong in SQL and a great asset to the CodingThis community.

    Latest posts by Basant Singh (see all)