0
type IA interface {
    Method()
}

type SA struct {
}

func (this *SA) Method() {

}


func main() {
    var i IA = SA{} //error 
    var i IA = &SA{} //ok
    var obj = SA{}

    obj.Method()//ok     

}   

Could you explain why does GO automatically dereference in the case of calling function (obj.Method()) but in assignment to interface variable (var i IA = SA{}) it can't?

Oleg
  • 624
  • 6
  • 12
  • Because the function expects a pointer (`*SA`) to a memory address. That's why `&SA{}` works, because you give it a memory-address. –  Mar 14 '15 at 11:09
  • Yes, but I asked why in the case of calling function GO does some underground (maybe puts obj from stack to heap and call with pointer). Maybe it can do the same things in the case of assignment, to store only pointer in interface variable? – Oleg Mar 14 '15 at 11:14
  • 2
    This http://golang.org/doc/faq#different_method_sets answers your question. – Grzegorz Żur Mar 14 '15 at 13:51
  • Yes, yours link addresses my question entirely, thanks. – Oleg Mar 14 '15 at 17:25

1 Answers1

2

func (this *SA) Method() means that only a pointer to type SA (*SA) has the Method() method, therefore var i IA = &SA{} fulfils the IA interface.

If you change it to read func (this SA) Method() then var i IA = SA{} fulfils the interface, and not var i IA = &SA{}.

*SA is not the same type as SA.

Go provides some shortcuts for dealing with dereferencing method values (which is probably where the confusion is coming from)

If you have a look at the Method Values section of the spec you will see that:

a reference to a non-interface method with a value receiver using a pointer will automatically dereference that pointer

and

a reference to a non-interface method with a pointer receiver using an addressable value will automatically take the address of that value

This is why obj.Method() works whether obj is an *SA or an SA.

Hope that helps.

Intermernet
  • 18,604
  • 4
  • 49
  • 61