-1

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)
paolo_losi
  • 283
  • 1
  • 7
  • 3
    You can't. The value in an interface is not addressable. If you need a pointer, put a pointer in the interface. – JimB Dec 09 '16 at 13:39
  • 2
    As JimB pointed out, it is not addressable. The interface value holds a copy of the original, so there would be no point. See related / possible duplicate question: [Types of Go struct methods that satisfy an interface](http://stackoverflow.com/questions/41015114/types-of-go-struct-methods-that-satisfy-an-interface/41016448#41016448) – icza Dec 09 '16 at 13:44
  • @icza. You really helped me to understad – paolo_losi Dec 10 '16 at 15:49

1 Answers1

1

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.

Abhishek Soni
  • 1,677
  • 4
  • 20
  • 27