Can Reflection in Go Facilitate Dynamic Interface Creation and Implementation?
Utilizing interfaces in Go, one can define RPC-style interfaces. For a specific service, an interface like the following might be created:
type MyService interface { Login(username, password string) (sessionId int, err error) HelloWorld(sessionId int) (hi string, err error) }
The goal is to leverage reflection to realize this interface by transforming method calls into RPC calls, marshalling input parameters, and unmarshalling results. While it is feasible to use reflection to obtain a []interface{} of input parameters for service calls, creating a value that dynamically implements an interface using reflection-based functions remains elusive.
Limitations and Alternative Approaches
It is not possible to generate a type with attached methods through reflection and subsequently instantiate an object of that type. While theoretically feasible using the unsafe package, it would be an arduous undertaking.
Instead, providing additional context on the problem you are attempting to address would allow the community to suggest alternative solutions.
Update (July 23, 2015)
Go 1.5 introduced reflect.FuncOf and reflect.MakeFunc, which provide the desired functionality.
The above is the detailed content of Can Go Reflection Dynamically Create and Implement Interfaces?. For more information, please follow other related articles on the PHP Chinese website!