The switch statement in Golang

The switch statement is one of the most important control flow in programming. It improves on the if-else chain in some cases. Thus making it substantially easy to do the same task with much less code. In this post, we will see how we can use the switch statement in the Go programming language.

What is Golang Switch Statement?

The switch statement is a control flow mechanism by which a program can give control to different segments for different cases. It consists of the switch expression and the case blocks. Switches in Go can work with any type of variable as we will see.

The switch statement syntax

The syntax for the switch statement is relatively simple. We have to use the “switch” keyword to start the switch block then values and after that, the block can have multiple cases that will match the value. Below is the syntax for the switch-case.

switch expression {
    case exp1: statement1
    case exp2: statement2
    case exp3: statement3
    ...
    default: statement4
}

The single-case switch statement

Switch-case in Go can have any number of case variables. Here is an example of a simple switch statement which only takes a single value to match. Later on, we will see that we can have as many as we want. So, here is the code for that.

package main

import (
	"fmt"
)

func c(v int) {
	switch v {
		case 42:
		fmt.Println("This is the answer!")
		case 45:
		fmt.Println("Not the answer")
		default:
		fmt.Println("The guess is wrong!")
	}
}

func main() {
	c(42)  // This is the answer!
	c(199) // The guess is wrong!
}

The multi-case switch statement

In the case block, we can have multiple values. That means if any of the values match then the block executes. Here is an example showing a multi-case switch statement.

package main

import (
	"fmt"
)

func c(v string) {
	switch v {
		case "John":
		fmt.Println("is an admin.")
		case "Kat", "Sally", "Kevin":
		fmt.Println("is an exployee")
	}
}

func main() {
	c("Kevin")  // is an exployee
	c("Sally")  // is an exployee
}

The “break” keyword

In the switch block, we can have the break keyword which will exit out of the entire block. The keyword has its own application. When we don’t want to run the case entirely we can simply use the break keyword. And that will allow us to exit from the block. Here is the break keyword in action.

package main

import (
	"fmt"
)

func f(v int) {
	switch v {
		case 1:
		fmt.Println("One")
		case 2:
		fmt.Println("Two")
		break
		// fmt.Println("Won't work") // will show the error "unreachable code"
		default:
		fmt.Println("The value is wrong")
			
	}
}

func main() {
	f(10)  // The value is wrong
	f(2)   // Two
}

The “fallthrough” keyword

Go has the fallthrough keyword which passes the execution to the next case. Now, sometimes we don’t want to go any further with the current case. We simply move on to the next one. The fallthrough keyword is just for that. The fallthrough keyword can be used as shown below.

package main

import (
	"fmt"
)

func f(c int) {
	switch c {
		case 2:
		fmt.Println("2")
		fallthrough
		case 4:
		fmt.Println("4")
		case 8:
		fmt.Println("8")
	}
}

func main() {
	f(2)   // 2
	       // 4
}

The switch statement with the variable initializer

The switch statement in Go can declare the variable first then use it at the same time. This is an optional statement, which is pretty handy at times. Here is shown how to initialize the variable with the switch statement.

package main

import (
	"fmt"
)

func main() {
	switch v := 3; v {
		case 1:
		break
		case 2:
		fallthrough
		case 3:
		fmt.Println("3")
	}
	
	// outputs 3
}

The switch statement with a predeclared variable

A variable declared before can be used in the switch statement as well. We can either check it at the time of the case declaration. Then we don’t need to put an expression after the switch keyword. Or, we can use that after the switch keyword and use it as a regular switch case. Examples of both are shown below.

package main

import (
	"fmt"
)

func main() {

	var v string = "Rob"
	
	// has an expression after switch
	switch v {
		case "Rob":              // just check the value
		fmt.Println("Hi, Rob!")
		default:
		fmt.Println("Hi, user!")
	}
	
	// doesn't have an expression after switch
	switch {  
		case v == "Rob":         // check the case here
		fmt.Println("Hi, Rob!")
		default:
		fmt.Println("Hi, user!")
	}

	// both of this work
}

The conditional case statement

Switches in Go can have conditions in the case. That means when the conditions match the block will execute. This is an example of using conditions in the cases.

package main

import (
	"fmt"
)

func main() {
	
	var v int = 10
	
	// no expression means it is true
	switch {
		case v < 5:
		fmt.Println("Less than 5")
		case v < 10:
		fmt.Println("Less than 10")
		case v < 15:
		fmt.Println("Less than 15")
		default:
		fmt.Println("Too large")
	}
	
	// output: Less than 15
	
}

The default case

The default case, as the name suggests is the block that will execute if none of the other values match. Here is an example using the default case.

package main

import (
	"fmt"
)

func main() {

	var v int = 10

	switch v{
		case 1:
		fmt.Println("One!")
		case 2:
		fmt.Println("Two!")
		case 3:
		fmt.Println("Three!")
		default:
		fmt.Println("Error!")
	}
	
	// output: Error!
}

Type-switches in Go

Go have type-switches, which allows using types instead of values in the switch statement. In the expression of the type-switch block, only interfaces can be used.

Golang Switch statement benefits

The switch statement can be used as a replacement for the if-else block. Sometimes it becomes verbose when we use the if-else block. At that point, the switch statement may be beneficial.