Home > other >  Get pointer type of a reflect.Type
Get pointer type of a reflect.Type

Time:07-15

Assume I only have a reflect.Type t:

fmt.Println(t) //prints lib.Counter

I would like to get pointer type to this type, such that:

fmt.Println(ptrT) //prints *lib.Counter

How can I do this? t can be of any type, not only lib.Counter.

Also, what if I want to do vice versa? Like getting lib.Counter from *lib.Counter?

CodePudding user response:

You can use reflect.PointerTo.

To get the non-pointer type again, you can use Type.Elem().

thing := Thing{}
ptrThing := &Thing{}

thingType := reflect.TypeOf(thing)
fmt.Println(thingType) // main.Thing
thingTypeAsPtr := reflect.PointerTo(thingType)
fmt.Println(thingTypeAsPtr) // *main.Thing

ptrThingType := reflect.TypeOf(ptrThing)
fmt.Println(ptrThingType) // *main.Thing
ptrThingTypeAsNonPtr := ptrThingType.Elem()
fmt.Println(ptrThingTypeAsNonPtr) // main.Thing

Working example: https://go.dev/play/p/29eXtdgI9Xf

CodePudding user response:

You can achieve that in the following way:

ptr := reflect.PointerTo(reflect.Typeof(lib.Counter{})) // *lib.Counter

The variable t can be an arbitrary type:

ptr := reflect.PointerTo(t)
  • Related