Different Ways to Find the Type of Variable in Golang

Here are three ways to find the type of variable in Go:

  1. Using reflect.TypeOf Function
  2. Using reflect.ValueOf.Kind() Function
  3. Using %T with Printf

Method 1: Using the reflect.TypeOf() function

The reflect.TypeOf() function accepts an input whose data type a user wants to know, and it returns its data type, and we can print it using the fmt.Print() function.

Example

package main

import (
  "fmt"
  "reflect"
)

func main() {
  var_data := "KB19"
  fmt.Print(reflect.TypeOf(var_data), "\n")
}

Output

string

You can see that the reflect.TypeOf() function with Print() function prints the data type of a variable in the console.

Method 2: Using the reflect.ValueOf.Kind() function

In Go, the reflect package provides a way to inspect the type and value of variables at runtime. The reflect.ValueOf() function returns a reflect.Value that represents the runtime value of the interface{}.

The Kind() method on a reflect.Value can then be used to retrieve the underlying type of the variable.

Example

package main

import (
 "fmt"
 "reflect"
)

func main() {
  var x int = 42
  var y string = "hello"
  var z float64 = 3.14

  checkType(x)
  checkType(y)
  checkType(z)
}

func checkType(v interface{}) {
  switch reflect.ValueOf(v).Kind() {
    case reflect.Int:
      fmt.Println("Type is int")
    case reflect.String:
      fmt.Println("Type is string")
    case reflect.Float64:
      fmt.Println("Type is float64")
    default:
      fmt.Println("Unknown type")
  }
}

Output

Type is int
Type is string
Type is float64

Method 3: Using the %T verb in fmt.Printf() function

The simplest and most recommended way of printing the type of a variable is to use the “%T verb in the fmt.Printf()” function.

Example

package main

import (
  "fmt"
)

func main() {
  var_data := "KB19"
  
  fmt.Printf("The type of variable is : %T\n", var_data)
}

Output

The type of variable is : string

In this example, we printed the string data type of a variable using the %T verb in fmt.Printf() function.