如何获取接口值的引用

huangapple go评论76阅读模式
英文:

how to obtain a reference to an interface value

问题

可以在不使用反射的情况下获取接口值的引用吗?如果不能,为什么不能?

我尝试了以下代码:

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)
英文:

Is it possibile to obtain a reference to an Interface Value without
reccurring to reflection? If not, why not?

I have attempted:

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

but it fails with:

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

答案1

得分: 1

清除你的疑惑,如果你按照"Assert"的意思来理解的话:

在你的例子中,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

希望我解决了你的困惑。

英文:

To clear your doubts if you go by the meaning Assert

> state a fact or belief confidently and forcefully

in your example x.(Foo) is just a type assertion it's not a object so you can not get its address.

so at runtime when the object will be created for example

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

it only assert that

> asserts that c is not nil and that the value stored in c is of type int

So its not any physical entity in memory but at runtime d will be allocated memory based on asserted type and than the contents of c will be copied into that location.

So you can do something like

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

Hope i cleared your confusion.

huangapple
  • 本文由 发表于 2016年12月9日 21:35:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/41061702.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定