How to get Type of declared variable in GoLang | GoLang Tutorial

5 years ago Lalit Bhagtani 0

In this tutorial, we will learn about how to get the Type of a variable in Go programming language.

GoLang TypeOf

The GoLang reflect package has a function for getting the type of a declared variable. The function TypeOf returns a Type, which can be converted to a string by calling String function.

Syntax

func TypeOf(i interface{}) Type

Example

package main

import (
    "fmt"
    "reflect"
)

// Package Level Constant
const name string = "CodeDestine"

// Package Level Variable
var (
    age         int32
    designation string
)

func main() {
    // Function Level Variable
    var (
	marks float64 = 10.32
    )
    fmt.Println(reflect.TypeOf(name).String())
    fmt.Println(reflect.TypeOf(age).String())
    fmt.Println(reflect.TypeOf(designation).String())
    fmt.Println(reflect.TypeOf(marks).String())
}

Printf function

Another way to get the Type of a variable is to use Printf method with %T option.

Syntax

fmt.Printf("%T", VariableName)

Example

package main

import (
    "fmt"
)

// Package Level Constant
const name string = "CodeDestine"

// Package Level Variable
var (
    age         int32
    designation string
)

func main() {
    // Function Level Variable
    var (
	 marks float64 = 10.32
    )
    fmt.Printf("%T\n", name)
    fmt.Printf("%T\n", age)
    fmt.Printf("%T\n", designation)
    fmt.Printf("%T\n", marks)
}

References

  1. TypeOf function Docs

That’s all for how to get the Type of a variable in Go programming language, if you liked it, please share your thoughts in comments section and share it with others too.