Table of Contents

Type switch

What is it?

A type switch lets you execute different code depending on the concrete type stored inside an interface value at runtime.

Syntax: `switch v := i.(type) { … }`

What is it used for?

Example

package main
 
import "fmt"
 
func handle(i any) {
    switch v := i.(type) {
    case int:
        fmt.Println("int:", v+1)
    case string:
        fmt.Println("string:", v+"!")
    default:
        fmt.Println("unknown type")
    }
}
 
func main() {
    handle(10)
    handle("go")
    handle(true)
}

Notes / pitfalls

Hard words (English)