设置传递给go中函数的接口值
我想换衣服设置传递给go中函数的接口值,go,Go,我想换衣服 Get(title string )(out interface{}) 例如: Get(title string,out interface{}) 这样我就可以通过引用传递接口,并让方法为我填充它,如: var i CustomInterface Get("title" , CustomInterface) i.SomeOperationWithoutTypeAssertion() //the i is nil here(my problem) func Get(title s
Get(title string )(out interface{})
例如:
Get(title string,out interface{})
这样我就可以通过引用传递接口,并让方法为我填充它,如:
var i CustomInterface
Get("title" , CustomInterface)
i.SomeOperationWithoutTypeAssertion() //the i is nil here(my problem)
func Get(title string,typ interface{}){
...
typ=new(ATypeWhichImplementsTheUnderlyingInterface)
}
<代码> >某个OutTySpSersService()/< >的操作不起作用,因为调用“<代码> > GET(“标题”,CustomInterface)< /Calp> < P> > GO没有在C++语言中发现的透明引用参数的概念,因此,NI是无效的。因此,您所要求的是不可能的:您的
Get
函数接收接口变量的副本,因此不会更新调用范围中的变量
如果确实希望函数能够更新作为参数传递的内容,则必须将其作为指针传递(即称为Get(“title”,&i)
)。没有语法指定参数应该是指向任意类型的指针,但所有指针都可以存储在接口{}
中,以便该类型可以用于参数。然后,您可以使用a/或来确定所给的类型。您需要依靠运行时错误或恐慌来捕获参数的错误类型
例如:
func Get(title string, out interface{}) {
...
switch p := out.(type) {
case *int:
*p = 42
case *string:
*p = "Hello world"
...
default:
panic("Unexpected type")
}
}
@OneOfOne:我想将接口作为引用传递,并让该方法初始化它。请给出建议,而不是否决,我需要通过引用传递接口,并让该方法通过实现传递的接口的类型的实例填充它。