我们如何将一个结构体嵌入到另一个结构体中并称之为嵌入结构体?

huangapple go评论72阅读模式
英文:

How we call an struct inside of another struct as embedded?

问题

为什么我们不把person字段称为“嵌入式”?

type user struct {
    name  string
    email string
}

type admin struct {
    person user // 不是嵌入式
    level  string
}

但在其他情况下,我们称之为嵌入式,如下所示:

type user struct {
    name  string
    email string
}

type admin struct {
    user  // 值语义嵌入式
    level string
}

我认为person也像值/指针语义嵌入式一样是嵌入式的。我在这里漏掉了什么?

英文:

Why we don't call person field as embedded?

“type user struct {
 name  string
 email string
}
 
type admin struct {
 person user  // NOT Embedding
 level  string
}”

But in other cases like below we call it embedded:

“type user struct {
 name  string
 email string
}
 
type admin struct {
 user  // Value Semantic Embedding
 level  string
}”

What I think is that person is also embedded like value/pointer semantic embedding. What I'm missing here?

答案1

得分: 3

因为这是Go语言规范中的定义:

声明了类型但没有显式字段名的字段被称为“嵌入字段”。

我可以理解“嵌入”这个术语可能会让人感到困惑。毕竟,有名字和无名字的字段最终都会以相同的内存布局“嵌入”到父结构体中。"匿名字段"可能是一个更好的名称,但这不是Go语言设计者选择的名称。

英文:

Because that's how the Go language specification defines it:

> A field declared with a type but no explicit field name is called an embedded field.

I can see how the term "embedded" would be confusing. After all, named and unnamed fields end up with the same memory layout, "embedded" into the parent struct. "Anonymous field" might have been a better name for it, but that's not the name that the Go language designers chose.

答案2

得分: 0

使用第一个代码,你不能将一个admin对象视为一个user对象,比如使用成员访问或类型断言。这也会影响到嵌入结构体如何满足interface的要求。

例如,下面的代码在正确嵌入时可以工作,但在简单成员结构体时不行:

var a admin

a.name = "asdfg"

u := a.(user)
英文:

With the first code you can't treat an admin object as a user object, like using member access or type assertion. This also affects how an embedding struct satisfies interfaces.

For example, the following code works with proper embedding, but not a simple member struct:

var a admin

a.name = "asdfg"

u := a.(user)

huangapple
  • 本文由 发表于 2022年7月24日 19:03:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/73097812.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定