using reflection in Go to get the name of a struct

前端 未结 3 919
刺人心
刺人心 2021-02-02 09:45

I found this question with this great answers:

How to find a type of a object in Golang?

I played around with the answer and tried to get the name of a struct in

3条回答
  •  醉酒成梦
    2021-02-02 09:50

    The problem is new returns pointer, following should get the desired result.

    package main
    
    import (
        "fmt"
        "reflect"
    )
    
    type Ab struct {
    }
    
    func getType(myvar interface{}) {
        valueOf := reflect.ValueOf(myvar)
    
        if valueOf.Type().Kind() == reflect.Ptr {
            fmt.Println(reflect.Indirect(valueOf).Type().Name())
        } else {
            fmt.Println(valueOf.Type().Name())
        }
    }
    
    func main() {
        fmt.Println("Hello, playground")
    
        tst := "string"
        tst2 := 10
        tst3 := 1.2
        tst4 := new(Ab)
    
        getType(tst)
        getType(tst2)
        getType(tst3)
        getType(tst4)
    
    }
    

    Output is

    Hello, playground
    string
    int
    float64
    Ab
    

提交回复
热议问题