Why is reflect.Type defined as an interface, but reflect.Value is defined as a struct?

133 views
Skip to first unread message

Hu Jian

unread,
Aug 17, 2023, 1:02:53 PM8/17/23
to golang-nuts
hi all,
I'm curious why reflect.Type is defined as an interface, but reflect.Value is defined as a struct? I don't see any other implementation of the reflect.Type interface.

Ian Lance Taylor

unread,
Aug 17, 2023, 4:54:12 PM8/17/23
to Hu Jian, golang-nuts
On Thu, Aug 17, 2023 at 10:02 AM Hu Jian <huji...@gmail.com> wrote:
>
> I'm curious why reflect.Type is defined as an interface, but reflect.Value is defined as a struct? I don't see any other implementation of the reflect.Type interface.

reflect.Value is an ordinary struct. The reflect.Type interface is
really implemented by several different types, each of which begins
with the same struct but is then followed by type-specific
information. On tip this is abi.PointerType, abi.StructType, and so
forth. That data structure can in turn be followed by
abi.UncommonType. So we have several possible implementations for
reflect.Type, although they all exist in the reflect package.

Also reflect.Value is small enough to pass around as a value, rather
than taking a pointer and sometimes forcing the Value into the heap
There's no reason to do that for reflect.Type, as we are normally
using pointers to data structures created by the compiler, not data
structures in the heap.

I think it's true that we could today push everything into a single
struct, and do all the pointer conversions behind the scenes, but it
wouldn't help much, and we can't make that change today anyhow.

Ian
Reply all
Reply to author
Forward
0 new messages