TExcelTAD
Home › Go › Go Type Assertions & Switches

Go Type Assertions & Type Switches

An interface value hides the concrete type stored inside it. Sometimes you need that concrete type back — to call a method that is not part of the interface, or to treat different types differently. Go gives you two tools: the type assertion and the type switch.

Type assertions

The expression x.(T) asserts that the interface value x holds a value of type T and returns it. Use the comma-ok form to test safely:

Form If x holds a T If not
v := x.(T) v is the value panics
v, ok := x.(T) v is the value, ok is true v is T's zero value, ok is false
go · try it yourself
package main

import "fmt"

func main() {
	var data any = "gopher"

	s := data.(string) // we are sure it is a string
	fmt.Println(s, len(s))

	if n, ok := data.(int); ok {
		fmt.Println("an int:", n)
	} else {
		fmt.Println("not an int; n is the zero value:", n)
	}
}
gopher 6
not an int; n is the zero value: 0

Without the ok, a wrong assertion stops the program:

go · try it yourself
package main

import "fmt"

func main() {
	defer func() {
		fmt.Println("recovered:", recover())
	}()

	var data any = 3.5
	n := data.(int)
	fmt.Println(n)
}
recovered: interface conversion: interface {} is float64, not int

Asserting to an interface

T can also be an interface. Then the assertion checks whether the value has those methods — a neat way to discover optional capabilities.

go · try it yourself
package main

import "fmt"

type Animal interface{ Name() string }
type Swimmer interface{ Swim() string }

type Dog struct{}
type Fish struct{}

func (Dog) Name() string  { return "dog" }
func (Fish) Name() string { return "fish" }
func (Fish) Swim() string { return "swims gracefully" }

func main() {
	zoo := []Animal{Dog{}, Fish{}}
	for _, a := range zoo {
		if s, ok := a.(Swimmer); ok {
			fmt.Println(a.Name(), s.Swim())
		} else {
			fmt.Println(a.Name(), "cannot swim")
		}
	}
}
dog cannot swim
fish swims gracefully

Type switches

When there are several possible types, a type switch is cleaner than a chain of assertions. It uses the special syntax x.(type), which is only allowed inside switch. In each case, the variable has that case's type.

go · try it yourself
package main

import (
	"fmt"
	"strings"
)

func describe(v any) string {
	switch x := v.(type) {
	case nil:
		return "nothing at all"
	case int:
		return fmt.Sprintf("int, doubled: %d", x*2)
	case string:
		return "string in caps: " + strings.ToUpper(x)
	case bool:
		if x {
			return "boolean yes"
		}
		return "boolean no"
	case []int:
		return fmt.Sprintf("slice with %d ints", len(x))
	case error:
		return "an error: " + x.Error()
	default:
		return fmt.Sprintf("something else (%T)", x)
	}
}

func main() {
	inputs := []any{21, "hello", true, []int{4, 5, 6}, fmt.Errorf("disk full"), 2.5, nil}
	for _, in := range inputs {
		fmt.Println(describe(in))
	}
}
int, doubled: 42
string in caps: HELLO
boolean yes
slice with 3 ints
an error: disk full
something else (float64)
nothing at all

A case can list several types (case int, int64:); then x keeps the interface type, because it could be either.

A practical use: walking JSON-like data

Decoded JSON (map[string]any) is a typical place where you meet type switches:

go · try it yourself
package main

import (
	"fmt"
	"maps"
	"slices"
)

func walk(prefix string, v any) {
	switch x := v.(type) {
	case map[string]any:
		for _, k := range slices.Sorted(maps.Keys(x)) {
			walk(prefix+"."+k, x[k])
		}
	case []any:
		for i, item := range x {
			walk(fmt.Sprintf("%s[%d]", prefix, i), item)
		}
	default:
		fmt.Printf("%s = %v\n", prefix, x)
	}
}

func main() {
	doc := map[string]any{
		"name": "ExcelTAD",
		"tags": []any{"go", "learning"},
		"meta": map[string]any{"stars": 42.0, "public": true},
	}
	walk("
quot;, doc) }
$.meta.public = true
$.meta.stars = 42
$.name = ExcelTAD
$.tags[0] = go
$.tags[1] = learning

Tip: If you find yourself writing many type switches, consider adding a method to an interface instead. Type switches are best at boundaries — decoding data, handling errors — not as a replacement for polymorphism.

Test yourself

What happens with n := v.(int) when v holds a string?

  1. n is 0
  2. It panics
  3. Compile error
  4. n is the string length

Where is the syntax v.(type) allowed?

  1. Anywhere
  2. Only in a type switch
  3. Only in if statements
  4. Only with any

In switch x := v.(type) { case string: ... }, what is the type of x inside the string case?

  1. any
  2. string
  3. interface{}
  4. type