Why allow an interface to have non-exported functions?

I noticed that reflect.Type is an interface, which briefly gave me hope that I can implement it to create new types dynamically in Go. But I also noticed that the interface “Has unexported methods” and I verified that I cannot implement it because of that.

I find this odd. Why allow public interfaces to not be implementable by anyone else? Why make it an interface then? Compare with reflect.Value which is a struct.

1 Like

For me, I think the Go team has a few reasons for making reflect. Type an interface with unexported methods. The few reasons I can think of are:-

  • Security: By making the methods unexported, It prevents the users from creating new types that could potentially break the Go runtime. For Instance, a user could create a new type that implements the io.Reader interface, but doesn’t actually read anything from the underlying data source. This could lead to data loss or other problems.

  • Performance:** By making the methods unexported, it optimizes the reflect.Type implementation for performance. It can avoid checking the receiver type for each method call.

  • Simplicity: By making the methods unexported, the Go team can keep the reflect.Type interface simple and easy to use. Go doesn’t need to worry about users accidentally calling the wrong method or passing the wrong arguments.

The reflect. Value struct is different because it is not used to represent the types of Go values. Instead, it is used to represent the values themselves. This means that there is no need to prevent users from creating new types, since the reflect.Value struct can only be used to reflect on existing values.

In Contrast, the Go team tries to strike a balance between security, performance, simplicity, and flexibility. In the case of reflect.Type, the Go team has decided that the benefits of making the methods unexported outweigh the drawbacks.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.