Type switches in Golang

A type-switch in Go is just like the switch statement but with types. In this post, we will go into details about the type-switches in Go. But first, we need to understand the switch statement.

What is a switch statement?

A switch statement is a control flow which checks for a condition to match and executes specific code for that matched value. Switch statements work like an if-else block. Here is an example switch case in Go.

package main

import (
	"fmt"
)

func f(s string) {
	switch s {
		case "a":
		fmt.Println("A")
		case "b":
		fmt.Println("B")
		case "c":
		fmt.Println("C")
		case "d":
		fmt.Println("D")
		default:
		fmt.Println("Default")
	}
}

func main() {
	f("a")    // A
	f("abc")  // default
}

In the code above the value passed at first is “a” which matches the first case. In the second case, the argument doesn’t match any case at all.

Go type-switches

Type switches are switch blocks where instead of a regular value a type is given in the form of an interface value. And then the type is matched and checked to perform the operations. The code below shows how to do that.

package main

import (
	"fmt"
)

func t(i interface{}) string {
	switch i.(type) {
		case string:
		return "A string value"
		case int:
		return "A number"
		default:
		return "Other"
	}
}

func main() {
	var a interface{} = "A sample string"
	fmt.Println(t(a)) // A string value
}

Why is it important?

Type switches allow us to run specific codes for specific types. This is a very important feature as it allows us to make our code concise and more correct.

Type-switches vs switch case

Type-switches are not much different than switch cases. They are essentially the same thing except type-switch can be used to check types and run type-specific code. This is what makes type-switches really useful. While a regular switch does the same thing without using types. The switch statement uses values.

Uses of type-switch in Golang

Anywhere an if-else block is going to be used with the type of the value, a type-switch can be used as well.