How to find the type of a variable in Golang

Last updated on Oct 21, 2022 by Suraj Sharma



In this tutorial, you will learn how you can find the type of a variable in Golang using the reflect module.


I will share two ways to find the type of Go variables



1. Using reflect.TypeOf() function


The TypeOf() function is available in the reflect package of Go. It takes a variable as an argument and returns the datatype of the variable.


Example


package main

import (
  "fmt"
  "reflect"
)

func main() {
    city := "New York"
  flag := true
    letters := []string{"A","B", "C"}
    priceMap := map[string]string{"apple": "$3", "tomato": "$2.99"}
    
  fmt.Println(reflect.TypeOf(city))    
  fmt.Println(reflect.TypeOf(flag))
  fmt.Println(reflect.TypeOf(letters))
  fmt.Println(reflect.TypeOf(priceMap))
    
}

**OUTPUT**

string
bool
[]string
map[string]string


Additionally, If you want to know whether a variable is a slice or a map you can use the TypeOf().Kind() function.


Example


package main

import (
  "fmt"
  "reflect"
)

func main() {
    letters := []string{"A","B", "C"}
    priceMap := map[string]string{"apple": "$3", "tomato": "$2.99"}
    
  fmt.Println(reflect.TypeOf(letters).Kind())
  fmt.Println(reflect.TypeOf(priceMap).Kind())
    
}

**OUTPUT**

slice
map


2. Print the type of variables directly using the “%T” verb


If you just want to print the type of a Go variable, you can use the “%T” verb in the fmt.Printf() function.

This way you don't have to use the reflect.TypeOf() function to first get the type of the variable.


Example


package main

import (
  "fmt"
)

func main() {
    city := "New York"
  flag := true
    letters := []string{"A","B", "C"}
    priceMap := map[string]string{"apple": "$3", "tomato": "$2.99"}
    
  fmt.Printf("%T\n", city)
  fmt.Printf("%T\n", flag)    
  fmt.Printf("%T\n", letters)
  fmt.Printf("%T\n", priceMap)
    
}

**OUTPUT**

string
bool
[]string
map[string]string


Related Solutions


Rate this post


Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.