Alex
Alex

Reputation: 397

Is it possible using reflection in golang to get the underlying type of a user defined type?

I have this type:

type T string

Can I get the underlying type of an object of T? For example:

package main

import (
    "fmt"
    "reflect"
)

type T string

func main() {
    var t = T("what")
    tt := reflect.TypeOf(t)
    fmt.Println(tt) // prints T, i need string
}

Upvotes: 2

Views: 630

Answers (2)

Adrian
Adrian

Reputation: 46582

Not exactly "the underlying type", but for your case, you don't want that, you want its Kind, from Type.Kind():

var t = T("what")
k := reflect.TypeOf(t).Kind()
fmt.Println(k)

Playable example: https://play.golang.org/p/M75wsTwUHkv

Note that Kind is not synonymous with "underlying type", which isn't really a thing, as you can see here: https://play.golang.org/p/900YGm2BnPV

Upvotes: 5

nos
nos

Reputation: 229324

You can call Type.Kind() , which will return you one of these constants

fmt.Println(tt.Kind()) // prints string

If you don't know if it's a pointer or not, you need an extra check and call Type.Elem()

var kind reflect.Kind 
if tt.Kind() == reflect.Ptr {
    kind = tt.Elem().Kind()
} else {
    kind = tt.Kind()
}
fmt.Println(kind)

Upvotes: 4

Related Questions