Reflect is a very useful built-in package, it contains some powerful funcs such as TypeOf, Kind, Value and etc.

I’ll try to document some of them here for future reference.

TypeOf

Have you ever wondered how to show the type of a struct object in golang? There’s no other simplier way as how they do it in python using type(), instead you have to import Reflect and use TypeOf or Kind to get it done. TypeOf covers Kind

func main() {
	a := struct {
		a int
		b string
	}{a: 123, b: "fsdfsd"}
	fmt.Println(reflect.TypeOf(a))
	fmt.Println(reflect.TypeOf(a.a))
	fmt.Println(reflect.TypeOf(a).Kind())
	fmt.Println(reflect.TypeOf(a.a).Kind())
}

output

struct { a int; b string }
int
struct
int

ValueOf

ValueOf extracts key’s value from a struct object.

	value := reflect.ValueOf(a)
	fmt.Println(value)

output

{123 fsdfsd}

Field

Field can be used to iterate item’s value. It also has built-in Kind() to show its key’s type.

Combine Together

// Example program to show difference between
// Type and Kind and to demonstrate use of
// Methods provided by Go reflect Package
package main

import (
	"fmt"
	"reflect"
)

type details struct {
	fname   string
	lname   string
	age     int
	balance float64
}

type myType string

func showDetails(i, j interface{}) {
	t1 := reflect.TypeOf(i)
	k1 := t1.Kind()
	t2 := reflect.TypeOf(j)
	k2 := t2.Kind()
	fmt.Println("Type of first interface:", t1)
	fmt.Println("Kind of first interface:", k1)
	fmt.Println("Type of second interface:", t2)
	fmt.Println("Kind of second interface:", k2)

	fmt.Println("The values in the first argument are :")
	if reflect.ValueOf(i).Kind() == reflect.Struct {
		value := reflect.ValueOf(i)
		numberOfFields := value.NumField()
		for i := 0; i < numberOfFields; i++ {
			fmt.Printf("%d.Type:%T || Value:%#v\n",
				(i + 1), value.Field(i), value.Field(i))

			fmt.Println("Kind is ", value.Field(i).Kind())
		}
	}
	value := reflect.ValueOf(j)
	fmt.Printf("The Value passed in "+
		"second parameter is %#v", value)
}

func main() {
	iD := myType("12345678")
	person := details{
		fname:   "Go",
		lname:   "Geek",
		age:     32,
		balance: 33000.203,
	}
	showDetails(person, iD)
}

output

Type of first interface: main.details
Kind of first interface: struct
Type of second interface: main.myType
Kind of second interface: string
The values in the first argument are :
1.Type:reflect.Value || Value:"Go"
Kind is  string
2.Type:reflect.Value || Value:"Geek"
Kind is  string
3.Type:reflect.Value || Value:32
Kind is  int
4.Type:reflect.Value || Value:33000.203
Kind is  float64
The Value passed in second parameter is "12345678"