How to find the type of an object in Go

Created
Modified

Using fmt.Sprintf Function

You can use fmt.Sprintf function to get a string representation. For example,

package main

import "fmt"

func main() {

  i := 10
  f := 2.0
  var m map[string]int

  s := fmt.Sprintf("%T", i)
  fmt.Printf("%q\n", s)

  s = fmt.Sprintf("%T", f)
  fmt.Printf("%q\n", s)

  s = fmt.Sprintf("%T", m)
  fmt.Printf("%q\n", s)
}
"int"
"float64"
"map[string]int"

%T a Go-syntax representation of the type of the value

Using reflect.TypeOf Function

TypeOf returns the reflection Type that represents the dynamic type of i.

package main

import (
  "fmt"
  "reflect"
)

func main() {

  i := 10
  f := 2.0
  var m map[string]int

  s := reflect.TypeOf(i).String()
  fmt.Printf("%q\n", s)

  s = reflect.TypeOf(f).String()
  fmt.Printf("%q\n", s)

  s = reflect.TypeOf(m).String()
  fmt.Printf("%q\n", s)

  s = reflect.TypeOf(m).Kind().String()
  fmt.Printf("%q\n", s)
}
"int"
"float64"
"map[string]int"
"map"
  • bug_reportreflect.TypeOf - gives type along with the package name.
  • bug_reportreflect.TypeOf().Kind() - gives underlining type.

Using Type Assertions

The primary expression x.(T). For example,

package main

import (
  "fmt"
)

func Typeof(v interface{}) string {
  switch v.(type) {
  case int:
    return "int"
  case float64:
    return "float64"
    // ... etc
  default:
    return "unknown"
  }
}

func main() {

  i := 10
  f := 2.0

  s := Typeof(i)
  fmt.Printf("%q\n", s)

  s = Typeof(f)
  fmt.Printf("%q\n", s)
}
"int"
"float64"

Based on a barebones benchmark, the reflect approach is surprisingly more efficient.

Related Tags

#find# #type# #object#