Web Development

Getting the type of a variable can be easily done with Go Lang using the reflect package.

Package reflect implements run-time reflection, allowing a program to manipulate objects with arbitrary types. The typical use is to take a value with static type interface{} and extract its dynamic type information by calling TypeOf, which returns a Type.

Go Lang Code to Get the Type

package main

import (
  "fmt"
  "reflect"
  "time"
)

func main() {
  var now time.Time = time.Now().UTC()
  fmt.Println("now is a type of: ", reflect.TypeOf(now))
  var name string = "Carl Johannes"
  fmt.Println("name is a type of: ", reflect.TypeOf(name))
  var age int = 5
  fmt.Println("age is a type of: ", reflect.TypeOf(age))
}

Output

$ go run type_of.go
now is:  time.Time
name is:  string
age is:  int

Easy, isn’t it?