Golang reflect.TypeOf: How to Find Data Type in Go

Finding a data type of variable is a repetitive task a developer must regularly perform. Converting one data type to another, checking if the variable has the same or a different data type, or printing in the console for debugging purposes. Every problem requires finding the current data type of the existing variable.

How to find a data type of a variable in Golang?

To find a variable’s data type in Golang, use the reflect.TypeOf() function. Another quick way to check the type of a value is by using the %T verb in conjunction with fmt.Printf() function.

In this article, we will talk about reflect.TypeOf() function and how it can be used to print the data type in runtime.

Golang reflect.TypeOf()

The reflect.TypeOf() is a built-in Golang function that returns the data type of a variable. The TypeOf() function accepts a variable as an argument and returns a runtime data type.

Syntax

func TypeOf(i interface{}) Type

Parameters

The TypeOf() function takes only one parameter, which is an interface.

Return value

It returns the reflection Type.

Implementation of reflect.TypeOf()

package main

import (
  "fmt"
  "reflect"
)

func main() {
  var num int64 = 10
  fmt.Print(reflect.TypeOf(num), "\n")
}

Output

int64

In this example, we declare an int64 variable to 10 and print its data type using the TypeOf() variable.

More examples

package main

import (
  "fmt"
  "reflect"
)

func main() {
  var_a := 10
  var_b := "KRUNAL"
  var_c := 1.9
  var_d := true
  var_e := map[string]int{"KL": 21, "KB": 19}
  var_f := []string{"SBF", "CZ"}

  fmt.Print(reflect.TypeOf(var_a), "\n")
  fmt.Print(reflect.TypeOf(var_b), "\n")
  fmt.Print(reflect.TypeOf(var_c), "\n")
  fmt.Print(reflect.TypeOf(var_d), "\n")
  fmt.Print(reflect.TypeOf(var_e), "\n")
  fmt.Print(reflect.TypeOf(var_f), "\n")
}

Output

int
string
float64
bool
map[string]int
[]string

Conclusion

To get a data type of a Go object, use the TypeOf() function of reflect package.

That’s it.

Leave a Comment