我正在尝试创建一个函数,该函数将创建接口的新实例,并将该实例分配给具有该接口类型的变量。这是一个简单的示例程序(无法编译):
package main
import (
"fmt"
)
type Foo interface {
Foo(int) int
}
type Foo_impl struct {}
func (f *Foo_impl) Foo(x int) int {
return x * 2
}
func main() {
var x *Foo_impl
constructFoo(x)
fmt.Println("Hello, playground")
}
func constructFoo(x Foo) {
*x = Foo_impl{} // Blows up here - invalid indirect of x (type Foo)
}
Run Code Online (Sandbox Code Playgroud)
是否可以通过反射间接接口变量并分配给底层值?如果我不使用接口,我会做这样的事情,
func main() {
var x int
foo(&x)
fmt.Printf("%d\n", x)
}
func foo(x *int) {
*x = 4
}
Run Code Online (Sandbox Code Playgroud)
正如预期的那样,这将打印出 4。问题是接口变量不能以正常方式间接访问。有没有解决的办法?
我能够编写一个函数来完成我想要的事情
package main
import (
"fmt"
"reflect"
)
type Y interface {
SetX(int)
}
type X struct {
test int
}
func (x *X) SetX(param int) {
x.test = param
}
func main() {
var x *X
y := foo(&x)
y.SetX(12)
fmt.Printf("%+v", x)
}
func foo(x interface{}) Y {
t := reflect.TypeOf(x)
pointerType := t.Elem()
realType := pointerType.Elem()
pointer := reflect.New(realType)
reflect.Indirect(reflect.ValueOf(x)).Set(pointer)
return pointer.Interface().(Y)
}
Run Code Online (Sandbox Code Playgroud)
该foo函数可以将任何双指针初始化为实现 的类型Y,并将新实例作为Y.
| 归档时间: |
|
| 查看次数: |
9520 次 |
| 最近记录: |