Can I create a new function using reflection in Go?

前端 未结 4 1679
醉话见心
醉话见心 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:20

    It appears that the reflect package will gain the ability to create new arbitrarily typed functions in Go 1.1: reflect.MakeFunc.

    (the following added in response to @nemo)

    Instead of an interface, one could create a struct type:

    type MyService struct{
      Login func(username, password string) (sessionId int, err error)
      HelloWorld func(sessionId int) (hi string, err error)
    }
    
    autorpc.ImplementService(&MyService, MyServiceURL)
    session, err := MyService.Login(username, password)
    stringout, err := MyService.HelloWorld(session)
    

提交回复
热议问题