On Wed, Dec 5, 2018 at 12:16 PM Burak Serdar <bser...@ieee.org> wrote:
> On Wed, Dec 5, 2018 at 10:12 AM Mark Volkmann <r.mark.volkm...@gmail.com> > wrote: > > > > I can get a reflect.Type for a variable with the following: myType := > reflect.TypeOf(myVariable) > > > > How can I get a reflect.Type for a type I have defined? > > For example: type MyThing struct { …bunch of fields… } > > I need to get a reflect.Type that describes the MyThing type. > > > > The best I can find is this: myThingType := > reflect.TypeOf(new(MyThing)).Elem() > > > myThingType:=reflect.TypeOf(MyThing{}) > This works for concrete types, but not for interfaces or named channel and function types. For interfaces, you can use a nil pointer: myThingType := reflect.TypeOf((*MyThing)(nil)).Elem() For channels and functions, you don't need a pointer or the Elem() call: myThingType := reflect.TypeOf(MyThing(nil)) The use of nil above is also good for named map type: the other suggestion above will allocate an unused empty map (though the compiler may optimize that away). > > > > > I seems odd that I have to create one with new, getting a pointer to it, > and then ask for the type of the thing in points to (with Elem) in order to > get what I need. > > > > -- > > R. Mark Volkmann > > Object Computing, Inc. > > > > -- > > You received this message because you are subscribed to the Google > Groups "golang-nuts" group. > > To unsubscribe from this group and stop receiving emails from it, send > an email to golang-nuts+unsubscr...@googlegroups.com. > > For more options, visit https://groups.google.com/d/optout. > > -- > You received this message because you are subscribed to the Google Groups > "golang-nuts" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to golang-nuts+unsubscr...@googlegroups.com. > For more options, visit https://groups.google.com/d/optout. > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.