0
0
GoConceptBeginner · 3 min read

What is Type Switch in Go: Explanation and Example

In Go, a type switch is a special form of switch statement that lets you compare the dynamic type of an interface variable against multiple types. It helps you run different code depending on the actual type stored inside an interface value.
⚙️

How It Works

A type switch in Go works like a regular switch but instead of comparing values, it compares the type of a variable that holds an interface. Imagine you have a box that can hold anything, but you want to know what exactly is inside to handle it properly. The type switch opens the box and checks the type of the item inside.

It uses the syntax switch v := x.(type), where x is the interface variable. Each case in the switch checks if the type matches a specific type, and if it does, the code inside that case runs. This is useful because Go is statically typed but interfaces can hold any type, so the type switch helps you safely find out what type you have at runtime.

💻

Example

This example shows how a type switch can detect the type of a variable and print a message accordingly.

go
package main

import "fmt"

func describe(i interface{}) {
    switch v := i.(type) {
    case int:
        fmt.Printf("This is an int: %d\n", v)
    case string:
        fmt.Printf("This is a string: %q\n", v)
    case bool:
        fmt.Printf("This is a bool: %t\n", v)
    default:
        fmt.Printf("Unknown type %T\n", v)
    }
}

func main() {
    describe(42)
    describe("hello")
    describe(true)
    describe(3.14)
}
Output
This is an int: 42 This is a string: "hello" This is a bool: true Unknown type float64
🎯

When to Use

Use a type switch when you have a variable of interface type and you need to perform different actions depending on the actual type stored inside. This is common when working with functions that accept any type (like interface{}) or when handling data from sources that can provide multiple types.

For example, in a program that processes user input or JSON data, you might receive values of different types and want to handle each type differently. Type switches let you write clear and safe code to do this without guessing or unsafe type assertions.

Key Points

  • A type switch checks the dynamic type of an interface variable.
  • It uses the syntax switch v := x.(type).
  • Each case handles a specific type safely.
  • It helps write clear code when dealing with multiple possible types.
  • Always include a default case to handle unexpected types.

Key Takeaways

A type switch lets you check the actual type inside an interface variable at runtime.
Use type switches to safely handle multiple types without errors.
The syntax is switch v := x.(type) with cases for each type.
Type switches are useful when working with generic or unknown data types.
Always provide a default case to catch unexpected types.