Can I create a new function using reflection in Go?

前端 未结 4 1728
醉话见心
醉话见心 2021-02-07 20:44

I have an idea to use interfaces in Go to define RPC style interfaces. So for a given service, I might create an interface like this:

type MyService interface{
          


        
4条回答
  •  故里飘歌
    2021-02-07 21:38

    Due to the static nature of the language, there is no way to implement an interface dynamically in Go at this point in time.

    I understand what you want to achieve and there are other scenarios that would also benefit of a more advanced reflection capability (e.g. a good mocking framework for unit tests)


    That said, there is a way that you could workaround this problem. You could write your own tool which generates a Go source code file containing a given RPC implementation of an interface.

    You would have to use the AST library, as well as others, to parse and process the source interface.

    Having gone down that path (gostub tool; can use as reference), I can say it is not at all fun and easy. Still, the end result is bearable since Go provides the go:generate functionality, which at least makes rerunning the tool, once an interface has changed, a tad easier.

提交回复
热议问题