doupao6011 2012-09-12 23:45
浏览 43
已采纳

我可以在Go中使用反射功能来创建新功能吗?

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{
  Login(username, password string) (sessionId int, err error)
  HelloWorld(sessionId int) (hi string, err error)
}

What I would like to do is use reflection to implement that interface, translating method calls into RPC calls, Marshaling the input parameters, and Unmarshaling the results back into the output of the method. I know that if I can get a []interface{} of the input parameters I can use reflection to make the service call. However I don't see any way to use reflection to dynamically create a value that would implement the interface by calling my reflection-using functions. Does anyone know of a way to do this, even using unsafe?

  • 写回答

4条回答 默认 最新

  • duanpie4763 2012-09-13 11:53
    关注

    You can not create a type with attached methods via reflection, as to instantiate an object of that type.

    You could possibly achieve this with a lot of hackery through the unsafe package. But even then, it'd be a massive pain.

    If you elaborated more on the problem you're trying to solve, the community could come up with alternatives ways of solving it.

    Edit (23. July 2015): starting with Go 1.5 there's reflect.FuncOf and reflect.MakeFunc, which do exactly what you want.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?