using reflection in Go to get the name of a struct

In your example you pass a value of pointer type (*Ab), not a struct type.

Sticking to Type.Name()

If it is not a pointer, Type.Name() will properly return Ab. In case of pointer if you still want the struct’s name, you can use Type.Elem() to get the element’s type:

func getType(myvar interface{}) string {
    if t := reflect.TypeOf(myvar); t.Kind() == reflect.Ptr {
        return "*" + t.Elem().Name()
    } else {
        return t.Name()
    }
}

Testing it:

tst4 := Ab{}
tst5 := new(Ab)
fmt.Println(getType(tst4))
fmt.Println(getType(tst5))

Output (try your modified example on the Go Playground):

Ab
*Ab

Note:

Note that as Type.Name() does not resolve pointers, it would not work if the value passed is a pointer to pointer, e.g. **Ab, while as Type.String() automatically resolves pointers, would work in this case too.

We can easily make our getType() function to work with **Ab too (or with any depth of pointers):

func getType(myvar interface{}) (res string) {
    t := reflect.TypeOf(myvar)
    for t.Kind() == reflect.Ptr {
        t = t.Elem()
        res += "*"
    }
    return res + t.Name()
}

Calling it with values:

tst4 := Ab{}
tst5 := new(Ab)
tst6 := &tst5 // type of **Ab
tst7 := &tst6 // type of ***Ab

Output (try it on the Go Playground):

Ab
*Ab
**Ab
***Ab

Using Type.String()

A simpler and better approach would be to use Type.String() instead of Type.Name() which automatically handles pointers and also includes package name. E.g.:

func getType(myvar interface{}) string {
    return reflect.TypeOf(myvar).String()
}

For the modified example it outputs:

string
int
float64
main.Ab
*main.Ab

Try this variant on the Go Playground.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)