Home >Backend Development >Golang >Can Go Reflection Create Functions Implementing Interfaces?
Using interfaces in Go to define RPC-style interfaces is a common practice. Consider the following example:
type MyService interface{ Login(username, password string) (sessionId int, err error) HelloWorld(sessionId int) (hi string, err error) }
To implement this interface using reflection, you would need to translate method calls into RPC calls, marshal the input parameters, and unmarshal the results back into the method's output.
However, there is no straightforward way to use reflection to create a value that would implement the interface by calling reflection functions.
The unsafe package could potentially allow for such a solution, but it would be extremely complex and prone to errors. It's not recommended to pursue this approach.
Rather than creating functions with reflection, consider exploring alternative solutions that align better with Go's design principles. Explain your specific problem or need to provide a more tailored recommendation.
Updates:
With the introduction of reflect.FuncOf and reflect.MakeFunc in Go 1.5, it is now possible to create functions with reflection as desired.
The above is the detailed content of Can Go Reflection Create Functions Implementing Interfaces?. For more information, please follow other related articles on the PHP Chinese website!