Skip to content

Golang Get the Type of Any Variable

Yes, you can get the type of any variable with TypeOf function from the reflect package:

func TypeOf(i interface{}) Type

Simplest example is here:

package main

import (
	"fmt"
	"reflect"
)

type User struct {
	Name string
	Age  int
}

func main() {
	age := 23
	name := "Morteza"
	userStruct := User{
		Name: name,
		Age:  age,
	}

	fmt.Println("type of age:", reflect.TypeOf(age))
	fmt.Println("type of name:", reflect.TypeOf(name))
	fmt.Println("type of userStruct:", reflect.TypeOf(userStruct))
}

Leave a Reply

Your email address will not be published. Required fields are marked *