Go core
Browse topics

Type switches

Version
1.27
Review
Draft

Summary#

A type switch selects the first case that matches the interface's dynamic type. An interface case matches types that implement it. A case that lists exactly one type gives the declared variable that type. In other clauses it keeps the type of the switched expression.

Syntax#

go
switch v := value.(type) {
case nil:
case int:
case bool, string:
default:
}

Example#

go
package main

import (
	"errors"
	"fmt"
)

func describe(value any) string {
	switch v := value.(type) {
	case nil:
		return "nil"
	case int:
		return fmt.Sprintf("int, next is %d", v+1)
	case string:
		return fmt.Sprintf("string of %d bytes", len(v))
	case error:
		return "error: " + v.Error()
	case bool, float64:
		return fmt.Sprintf("other scalar: %v", v)
	default:
		return fmt.Sprintf("unhandled %T", v)
	}
}

func main() {
	values := []any{nil, 41, "go", errors.New("offline"), true, []int{1}}
	for _, value := range values {
		fmt.Println(describe(value))
	}
}

Expected output#

Text
nil
int, next is 42
string of 2 bytes
error: offline
other scalar: true
unhandled []int

Common mistakes#

A case such as int, int64 leaves v with the interface type, so arithmetic on it does not compile. Split the cases when you need the concrete type. A nil pointer inside an interface can match a case for its pointer type. Use case nil for a nil interface and errors.As to find a type inside a wrapped error. fallthrough is not permitted.

Version applicability#

Type switches date back to Go 1.0. The complete example requires Go 1.18 for any. Use interface{} for earlier versions. The separate errors.As helper requires Go 1.13.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0