How to Print Type of Variable in Golang

To print a type of variable in Golang, you can use the “%T verb in the fmt.Printf()” function or the “reflect.TypeOf()” function.

Method 1: 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.

Method 2: Using the reflect.TypeOf() function

Alternatively, you can use the “reflect.TypeOf()” function to check the data type in Go. 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.

Leave a Comment