如何获取对接口值的引用

时间:2016-12-09 13:35:47

标签: go

是否可以在没有的情况下获得对接口值的引用 反复思考?如果没有,为什么不呢?

我试过了:

package foo

type Foo struct {
    a, b int
}

func f(x interface{}) {
    var foo *Foo = &x.(Foo)
    foo.a = 2
}

func g(foo Foo) {
    f(foo)
}

但它失败了:

./test.go:8: cannot take the address of x.(Foo)

1 个答案:

答案 0 :(得分:1)

如果你遵循含义Assert

,请清除你的怀疑
  

自信而有力地陈述事实或信念

在您的示例中{p> x.(Foo)只是一个类型断言,它不是一个对象,因此您无法获取其地址。

因此在运行时将创建对象,例如

var c interface{} = 5
d := c.(int)
fmt.Println("Hello", c, d)  // Hello 5 5

它只断言

  

断言c不是nil,并且存储在c中的值是int

类型

因此,它不是内存中的任何物理实体,而是在运行时d将根据断言类型分配内存,而c的内容将被复制到该位置。

所以你可以做点什么

var c interface{} = 5
d := &c
fmt.Println("Hello", (*d).(int)) // hello 5
希望我能清除你的困惑。