Home > front end >  How we call an struct inside of another struct as embedded?
How we call an struct inside of another struct as embedded?

Time:07-24

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?

CodePudding user response:

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.

CodePudding user response:

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)
  • Related