如何通过引用传递接口并让方法为我填充它?像这样的东西:
var i CustomInterface
Get("title" , ref i)
i.SomeOperationWithoutTypeAssertion() //i is nil here(my problem)
func Get(title string, iRef ref interface{}){
iRef = new(ATypeWhichImplementsTheUnderlyingInterface)
}
I want i
调用后不为零Get
方法。如何通过i
作为参考Get
method?
Go 没有 C++ 等语言中的透明引用参数的概念,所以你所要求的是不可能的:Get
函数接收接口变量的副本,因此不会更新调用范围中的变量。
如果您确实希望函数能够更新作为参数传递的内容,那么它必须作为指针传递(即称为Get("title", &i)
)。没有语法指定参数应该是指向任意类型的指针,但所有指针都可以存储在interface{}
这样该类型就可以用于参数。然后您可以使用类型断言 https://golang.org/ref/spec#Type_assertions / switch https://golang.org/ref/spec#Type_switches or the reflect package http://golang.org/pkg/reflect/以确定您被赋予的类型。您需要依靠运行时错误或恐慌来捕获参数的错误类型。
例如:
func Get(title string, out interface{}) {
...
switch p := out.(type) {
case *int:
*p = 42
case *string:
*p = "Hello world"
...
default:
panic("Unexpected type")
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)