What is the reflect.TypeOf() Method in Golang

The reflect.TypeOf() is a Go function used to get the reflection Type that represents the dynamic type of input. It accepts a variable as an argument and returns a runtime data type.

To use the TypeOf() function in Go, you need to import the “reflect” package.

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.

Example 1

package main

import (
  "fmt"
  "reflect"
)

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

Output

int64

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

Example 2

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

That’s it.

Leave a Comment