Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get pointer type of a reflect.Type

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading