Why can't I assign type's value to an interface implementing methods with receiver type pointer to that type?

前端 未结 4 1835
借酒劲吻你
借酒劲吻你 2021-02-08 19:53

I am 2-days old in the world of Golang, and going through the go tour. I couldn\'t help but notice a peculiarity which I cannot seem to be able to come at terms with a

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-08 20:26

    "Intro++ to Go Interfaces" illustrates the issue:

    *Vertex is a type. It’s the “pointer to a Vertex” type. It’s a distinct type from (non-pointer) Vertex. The part about it being a pointer is part of its type.

    You need consistency of type.

    "Methods, Interfaces and Embedded Types in Go":

    The rules for determining interface compliance are based on the receiver for those methods and how the interface call is being made.
    Here are the rules in the spec for how the compiler determines if the value or pointer for our type implements the interface:

    • The method set of the corresponding pointer type *T is the set of all methods with receiver *T or T

    This rule is stating that if the interface variable we are using to call a particular interface method contains a pointer, then methods with receivers based on both values and pointers will satisfy the interface.

    • The method set of any other type T consists of all methods with receiver type T.

    This rule is stating that if the interface variable we are using to call a particular interface method contains a value, then only methods with receivers based on values will satisfy the interface.

    Karrot Kake's answer about method set is detailed also in go wiki:

    The method set of an interface type is its interface.

    The concrete value stored in an interface is not addressable, in the same way that a map element is not addressable.
    Therefore, when you call a method on an interface, it must either have an identical receiver type or it must be directly discernible from the concrete type.

    Pointer- and value-receiver methods can be called with pointers and values respectively, as you would expect.
    Value-receiver methods can be called with pointer values because they can be dereferenced first.
    Pointer-receiver methods cannot be called with values, however, because the value stored inside an interface has no address.

    ("has no address" means actually that it is not addressable)

提交回复
热议问题