How to Check the Type of a Value in Go
A quick way to check the type of a value in Go is by using the %T
fmt verb in conjunction with
fmt.Printf()
. Here’s an example:
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)
}
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
Alternatively, the reflect.TypeOf()
method gives similar results:
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))
}
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 in Go
If you have an interface{}
value and you want to check 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")
}
}
s is a string
If s
holds a string value, the ok
variable will be true. Otherwise, it will
be false
.
Thanks for reading, and happy coding!