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?

4
  • Because the function expects a pointer (*SA) to a memory address. That's why &SA{} works, because you give it a memory-address. Commented Mar 14, 2015 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? Commented Mar 14, 2015 at 11:14
  • 2
    This golang.org/doc/faq#different_method_sets answers your question. Commented Mar 14, 2015 at 13:51
  • Yes, yours link addresses my question entirely, thanks. Commented Mar 14, 2015 at 17:25

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. But I didn't ask about why is it error.I asked why it can't be dereferenced var i IA = SA{} automatically by GO compiler
because SA{} doesn't satisfy the IA interface.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.