英文:
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 interface
s.
For example, the following code works with proper embedding, but not a simple member struct:
var a admin
a.name = "asdfg"
u := a.(user)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论