且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我不能将类型的值分配给实现带有接收者类型指针的方法的接口?

更新时间:2022-05-07 01:03:43

" Intro ++ to Go Interfaces "说明了此问题:

* Vertex 是一种类型.这是指向 Vertex 的指针"类型.它是与(非指针) Vertex 不同的类型.关于它是指针的部分是其类型的一部分.

*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.

您需要类型的一致性.

" Go中的方法,接口和嵌入式类型":

确定接口符合性的规则基于这些方法的接收者以及如何进行接口调用.
规范中的规则是有关编译器如何确定我们类型的值或指针是否实现接口的规则:

  • 相应指针类型 * T 的方法集是具有接收者 * T T
  • 的所有方法的集合

    • 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.

      • 任何其他类型 T 的方法集由所有接收方类型为 T 的方法组成.
        • 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 方法集 的6309> answer 详细也在 go Wiki 中:

          接口类型的方法集是其接口.

          The method set of an interface type is its interface.

          接口中存储的具体值不可寻址,就像 map 元素不可寻址一样.
          因此,当您在接口上调用方法时,该方法必须具有相同的接收器类型,或者必须与具体类型可以直接区分.

          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)