On Wed, Mar 25, 2015 at 4:20 PM, <
ego...@gmail.com> wrote:
>
> TL;DR; version: `reflect.TypeOf(MyType{})` vs
> `reflect.TypeOf((*MyType)(nil)).Elem()`
>
> I am exploring the `reflect` package, and was wondering what is the right
> way to get a hold of a reflect.Type for a given struct.
>
> I saw some samples doing reflect.TypeOf(MyType{}) but wouldn't that cause an
> allocation of a MyType instance in memory or would the compiler be smart
> enough to not even cause the allocation (since there are no actual
> references to it)?
In principle it reflect.TypeOf(MyType{}) should not require any heap
allocation, since the value does not escape. However, I don't know
offhand if the current compiler is smart enough to see that.
> the alternative is to do reflect.TypeOf((*MyType)(nil)).Elem()
Yes, that works.
> Also, reflect.TypeOf considered heavyweight and results should be cached for
> recurring usage? if so, the single extra allocation is not a biggie and the
> intent is clearer over the *nil syntax IMO
reflect.TypeOf is fast. It's just a few instructions.
Ian