dongxiaoying5882 2018-06-26 15:15
浏览 11
已采纳

Go中接口类型的间接

I'm trying to create a function that will create a new instance of an interface, and assign that instance to a variable that has the type of the interface. Here is a simple example program (which does not compile):

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)
}

Is it possible via reflection to indirect an interface variable, and assign to the underlying value? If I were not using interfaces, I would do something like this,

func main() {
    var x int
    foo(&x)
    fmt.Printf("%d
", x)
}

func foo(x *int) {
    *x = 4
}

And as expected, this will print out 4. The issue is that interface variables cannot be indirected in the normal way. Is there a way around this?

  • 写回答

6条回答 默认 最新

  • douyan8070 2018-06-26 18:51
    关注

    I was able to write a function that did what I want

    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)
    }
    

    The foo function can initialize any double pointer to a type that implements Y, and it returns the new instance as a Y.

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

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog