How to check the type of a value in Go

The following code snippets show different ways to access the type of a variable in Go

A quick way to check the type of a value in Go is by using the %T verb in conjunction with fmt.Printf. This works well if you want to print the type to the console for debugging purposes.

package main

import (
	"fmt"
)

func main() {
	a, b, c := "yes", 20.6, false
	d := []int{3, 4, 5, 6}
	e := map[string]string{
		"name":  "jake",
		"email": "jake@example.com",
	}
	fmt.Printf("type of a is %T\n", a)
	fmt.Printf("type of b is %T\n", b)
	fmt.Printf("type of c is %T\n", c)
	fmt.Printf("type of d is %T\n", d)
	fmt.Printf("type of e is %T\n", e)
}
output
type of a is string
type of b is float64
type of c is bool
type of d is []int
type of e is map[string]string

An alternative way to determine the type of a value is to use the TypeOf method from the reflect package:

package main

import (
	"fmt"
	"reflect"
)

func main() {
	a, b, c := "yes", 20.6, false
	d := []int{3, 4, 5, 6}
	e := map[string]string{
		"name":  "jake",
		"email": "jake@example.com",
	}
	fmt.Printf("type of a is %v\n", reflect.TypeOf(a))
	fmt.Printf("type of b is %v\n", reflect.TypeOf(b))
	fmt.Printf("type of c is %v\n", reflect.TypeOf(c))
	fmt.Printf("type of d is %v\n", reflect.TypeOf(d))
	fmt.Printf("type of e is %v\n", reflect.TypeOf(e))
}
output
type of a is string
type of b is float64
type of c is bool
type of d is []int
type of e is map[string]string

Type assertions

If you have an interface value and you want to check the value of its underlying type, you need to use a type assertion in the following form:

v, ok := i.(T)

Here’s an example:

package main

import (
	"fmt"
)

func main() {
	var s interface{} = "string"
	if _, ok := s.(string); ok {
		fmt.Println("s is a string")
	} else {
		fmt.Println("s is not a string")
	}
}
output
s is a string

If s holds a string value, the ok variable will be true. Otherwise, it will be false. This is how to check the type of an interface value at runtime.