Switch Statement in Go

Switch Statement in Go

In this tutorial, we are going to discuss switch statement in Go language. Go language also supports a switch statement similar to that found in other languages such as PHP or Java.

Switch Statement in Go

Switch statements are an alternative way to express lengthy if-else comparisons into more readable code based on the state of a variable.

A switch is a conditional statement that evaluates an expression, compares it against a list of possible matches, and executes the corresponding block of code.

Everything we can write with the switch statement can also be written with if statements.

Switch is commonly used to describe the actions taken by a program when a variable is assigned specific values. The following example demonstrates how we would accomplish this using if statements

package main

import "fmt"

func main() {
	flavors := []string{"Chocolate", "Vanilla", "Strawberry", "Banana"}
	for _, flav := range flavors {
		if flav == "Strawberry" {
			fmt.Println(flav, "is my favorite flavor.!!")
			continue
		}
		if flav == "Vanilla" {
			fmt.Println(flav, "is good flavor.!!")
			continue
		}
		if flav == "Chocolate" {
			fmt.Println(flav, "is average flavor.!!")
			continue
		}
		fmt.Println("I've never tried", flav, "flavor before..!!")
	}
}

Output

Chocolate is average flavor.!! 
Vanilla is good flavor.!! 
Strawberry is my favorite flavor.!! 
I've never tried Banana flavor before..!!

Run in playground

The following example converts the previous example to use a switch instead of multiple if statements.

package main

import "fmt"

func main() {
	flavors := []string{"Chocolate", "Vanilla", "Strawberry", "Banana"}
	for _, flav := range flavors {
		switch flav {
		case "Strawberry":
			fmt.Println(flav, "is my favorite flavor.!! ")
		case "Vanilla", "Chocolate":
			fmt.Println(flav, "is good flavor.!!")
		default:
			fmt.Println("I've never tried", flav, "flavor before..!!")
		}
	}
}

The output is the same as before

Chocolate is average flavor.!! 
Vanilla is good flavor.!! 
Strawberry is my favorite flavor.!! 
I've never tried Banana flavor before..!!

Run in playground

Duplicate cases are not allowed

Duplicate cases with the same constant value are not allowed. If you try to run the program below, the compiler will give an error.

package main

import (
	"fmt"
)

func main() {
	number := 4
	switch number {
	case 1:
		fmt.Println("Number is ", number)
	case 2:
		fmt.Println("Number is ", number)
	case 3:
		fmt.Println("Number is ", number)
	case 4:
		fmt.Println("Number is ", number)
	case 4: //duplicate case
		fmt.Println("Number is ", number)
	case 5:
		fmt.Println("Number is ", number)
	}
}

Output

./prog.go:19:7: duplicate case 4 in switch previous case at ./prog.go:17:7
Multiple expressions in case

In Go language, it is possible to include multiple expressions in a case by separating them with comma.

package main

import (
    "fmt"
)

func main() {
    letter := "a"
    fmt.Printf("Letter %s is a ", letter)
    switch letter {
    case "a", "e", "i", "o", "u": //multiple expressions in case
        fmt.Println("vowel")
    default:
        fmt.Println("not a vowel")
     }
 }

Output

Letter a is a vowel

Run in playground

The above program finds whether the letter is a vowel or not. The code case “a”, “e”, “i”, “o”, “u”: in line no. 11 matches any of the vowels.

Expressionless switch

The expression in a switch is optional and it can be omitted.

If the expression is omitted, the switch is considered to switch true, and each of the case expression is evaluated for truth, and the corresponding block of code is executed.

package main

import (
    "fmt"
)

func main() {
     num := 25
     switch { // expression is omitted
     case num >= 0 && num <= 50:
         fmt.Printf("%d is greater than 0 and less than 50", num)
     case num >= 51 && num <= 100:
         fmt.Printf("%d is greater than 51 and less than 100", num)
     case num >= 101:
         fmt.Printf("%d is greater than 100", num)
    }
}

Output

25 is greater than 0 and less than 50

In the above example, the expression is absent in switch, and hence it is considered true, and each of the cases is evaluated.

Fallthrough

In Go language, the control comes out of the switch statement immediately after a case is executed.

Sometimes you will want to reuse the code that another case clause contains. In these cases, it’s possible to ask Go to run the body of the next case clause listed using the fallthrough keyword.

package main

import "fmt"

func main() {
    flavors := []string{"Chocolate", "Vanilla", "Strawberry", "Banana"}

    for _, flav := range flavors {
        switch flav {
        case "Strawberry":
            fmt.Println(flav, "is my favorite flavor.!!")
            fallthrough
        case "Vanilla", "Chocolate":
            fmt.Println(flav, "is good flavor.!!")
        default:
            fmt.Println("I've never tried", flav, "flavor before.!!")
        }
    }
}

Output

Chocolate is good flavor.!!
Vanilla is good flavor.!! 
Strawberry is my favorite flavor.!! 
Strawberry is good flavor.!! 
I've never tried Banana flavor before.!!

Run in playground

Please note that fall through will happen even when the case evaluates to false.

That’s all about the Switch Statement in Go language. If you have any queries or feedback, please write us email at contact@waytoeasylearn.com. Enjoy learning, Enjoy Go language.!!

Switch Statement in Go
Scroll to top