我可以在Go中使用反射来创建一个新功能吗? [英] Can I create a new function using reflection in Go?

查看:207
本文介绍了我可以在Go中使用反射来创建一个新功能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个想法,使用Go中的接口来定义RPC风格的接口。所以对于一个给定的服务,我可能会创建一个如下所示的接口:

  type MyService interface {
Login(username,密码字符串)(sessionId int,err错误)
HelloWorld(sessionId int)(hi string,err error)
}

我想要做的就是使用反射来实现该接口,将方法调用转换为RPC调用,对输入参数进行编组,并将结果解组为方法的输出。我知道,如果我可以获得输入参数的[]接口,我可以使用反射来进行服务调用。不过,我没有看到任何方式使用反射动态创建一个值,通过调用我的反射使用函数来实现接口。有人知道这样做的方法,即使使用不安全吗?

,以实例化该类型的对象。



您可能通过 unsafe 包。但即使如此,这将是一个巨大的痛苦。



如果您详细阐述了您正试图解决的问题,社区可以提出替代方法解决它。



编辑(2015年7月23日):从Go 1.5开始,有 reflect.FuncOf reflect.MakeFunc ,它完全符合你的要求。


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?

解决方案

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.

这篇关于我可以在Go中使用反射来创建一个新功能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆