Dowemo
0 0 0 0


Question:

How Do I find type of an object in Golang ? In Python I just use typeof to fetch the type of object. Similarly in Go, is there a way to implement the same ?

Here is the container from which I am iterating

for e := dlist.Front(); e != nil; e = e.Next() {
    lines := e.Value
    fmt.Printf(reflect.TypeOf(lines))
   }

I am not able to get the type of the object lines in this case which is a array of strings.


Best Answer:


Use 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.

package main
import (
    "fmt"
    "reflect"
)
func main() {
    b := true
    s := ""
    n := 1
    f := 1.0
    a := []string{"foo", "bar", "baz"}
    fmt.Println(reflect.TypeOf(b))
    fmt.Println(reflect.TypeOf(s))
    fmt.Println(reflect.TypeOf(n))
    fmt.Println(reflect.TypeOf(f))
    fmt.Println(reflect.TypeOf(a))
}

Produces:

bool
string
int
float64
[]string

Playground

Example using ValueOf(i interface{}).Kind():

package main
import (
    "fmt"
    "reflect"
)
func main() {
    b := true
    s := ""
    n := 1
    f := 1.0
    a := []string{"foo", "bar", "baz"}
    fmt.Println(reflect.ValueOf(b).Kind())
    fmt.Println(reflect.ValueOf(s).Kind())
    fmt.Println(reflect.ValueOf(n).Kind())
    fmt.Println(reflect.ValueOf(f).Kind())
    fmt.Println(reflect.ValueOf(a).Index(0).Kind()) // For slices and strings
}

Produces:

bool
string
int
float64
string

Playground




Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs