go - 匿名/显式在结构中嵌入接口(interface)

标签 go interface

type A interface {
    f()
}

type B struct {
    A
}

type C struct {
    Imp A
}

func main() {
    b := B{}
    c := C{}
    //b can be directly assigned to the A interface, but c prompts that it cannot be assigned
    var ab A = b
    //Cannot use 'c' (type C) as type A in assignment Type does not implement 'A' as some methods are missing: f() 
    var ac A = c
}

B 结构和 C 结构有什么不同?

在 Go 工作表中

A field declared with a type but no explicit field name is called an embedded field. An embedded field must be specified as a type name T or as a pointer to a non-interface type name *T, and T itself may not be a pointer type. The unqualified type name acts as the field name.

最佳答案

如果您继续阅读相同内容 section of the spec阅读规范,您会注意到以下内容:

Given a struct type S and a defined type T, promoted methods are included in the method set of the struct as follows:

  • If S contains an embedded field T, the method sets of S and *S both include promoted methods with receiver T. The method set of *S also includes promoted methods with receiver *T.
  • If S contains an embedded field *T, the method sets of S and *S both include promoted methods with receiver T or *T.

您的结构 B 没有显式定义的方法,但 B 的方法集隐式包含嵌入字段中提升的方法 。在本例中,嵌入字段是带有方法 f() 的接口(interface)。您可以使用满足该接口(interface)的任何对象,其 f() 方法将自动成为 B 方法集的一部分。

另一方面,您的 C 结构有一个命名字段。 Imp 上的方法不会自动添加到 C 的方法集中。相反,要从 Imp 访问 f() 方法,您需要专门调用 C.Imp.f()

最后:您使用接口(interface)作为(嵌入或非嵌入)字段这一事实并不重要,它很可能是另一个具有 f() 方法的结构。 重要的是f()是否成为父结构体方法集的一部分,这将允许它实现A

关于go - 匿名/显式在结构中嵌入接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63354935/

相关文章:

c++11 - 获取模板以与 C++ 中的接口(interface)的 unique_ptr 良好配合

.net - 什么破坏了 .net 二进制 (dll) 接口(interface)

java - 在 Java 中重载内部接口(interface)

assembly - "MOVOU"在golang汇编中是什么意思

java - 指示要在属性文件中运行的类?

golang.org/x/crypto/bcrypt 生成哈希时的错误案例

Goquery 从明显不是空的响应中加载空文档

Java 8 : When the use of Interface static methods becomes a bad practice?

pointers - 尽管映射始终是引用类型,但如果它们是从非指针接收器返回的呢?

go - 在go中将int32转换为字节数组