2

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
}
Pika Supports Ukraine
  • 3,612
  • 10
  • 26
  • 42
Alex
  • 367
  • 4
  • 15
  • See related: [Identify non builtin-types using reflect](https://stackoverflow.com/questions/36310538/identify-non-builtin-types-using-reflect/37292523#37292523). – icza Nov 01 '18 at 15:17

2 Answers2

5

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

sepehr
  • 5,479
  • 3
  • 29
  • 33
Adrian
  • 42,911
  • 6
  • 107
  • 99
  • if `t` is of type `*T` can I still get to the "underlying type"? i.e. `string` and not `ptr` – Alex Nov 01 '18 at 15:12
  • Yes. See [`Type.Elem()`](https://golang.org/pkg/reflect/#Type). https://play.golang.org/p/c64GDPglcwh – Adrian Nov 01 '18 at 15:15
4

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)
nos
  • 223,662
  • 58
  • 417
  • 506