Sunday, 12 May 2019

Go language: Find type of object


Approach 1: Using 'reflect.TypeOf' method

App.go
package main

import (
	"fmt"
	"reflect"
)

type Employee struct {
	Name string
	ID   int
}

func main() {

	i := 10
	j := 10.11
	k := "Krishna"
	emp := Employee{}

	fmt.Println("Type of i : ", reflect.TypeOf(i))
	fmt.Println("Type of j : ", reflect.TypeOf(j))
	fmt.Println("Type of k : ", reflect.TypeOf(k))
	fmt.Println("Type of emp : ", reflect.TypeOf(emp))
}

Output
Type of i :  int
Type of j :  float64
Type of k :  string
Type of emp :  main.Employee

Approach 2: Using fmt.Sprintf("%T", v)


App.go
package main

import (
	"fmt"
)

type Employee struct {
	Name string
	ID   int
}

func main() {

	i := 10
	j := 10.11
	k := "Krishna"
	emp := Employee{}

	fmt.Println("Type of i : ", fmt.Sprintf("%T", i))
	fmt.Println("Type of j : ", fmt.Sprintf("%T", j))
	fmt.Println("Type of k : ", fmt.Sprintf("%T", k))
	fmt.Println("Type of emp : ", fmt.Sprintf("%T", emp))
}

Output
Type of i :  int
Type of j :  float64
Type of k :  string
Type of emp :  main.Employee

Approach 3: Using reflect.ValueOf(variable).Kind()


App.go
package main

import (
	"fmt"
	"reflect"
)

type Employee struct {
	Name string
	ID   int
}

func main() {

	i := 10
	j := 10.11
	k := "Krishna"
	emp := Employee{}

	fmt.Println("Type of i : ", reflect.ValueOf(i).Kind())
	fmt.Println("Type of j : ", reflect.ValueOf(j).Kind())
	fmt.Println("Type of k : ", reflect.ValueOf(k).Kind())
	fmt.Println("Type of emp : ", reflect.ValueOf(emp).Kind())
}

Output
Type of i :  int
Type of j :  float64
Type of k :  string
Type of emp :  struct

As you see the output, kind() method returns ‘struct’ for a struct of type Employee, whereas previous two approaches return main.Employee.

reflect.TypeOf, fmt.Sprintf gives type along with the package name.

reflect.TypeOf().Kind() gives underlining type.




Previous                                                 Next                                                 Home

No comments:

Post a Comment