Is the following code is an example of Embedded Struct or Nested Struct or something else? And Are we using one struct type (person) in another type struct (secretAgent) ?
package main
import "fmt"
type person struct {
first string
last string
age int
}
type secretAgent struct {
person
ltk bool
}
func main() {
sa1 := secretAgent{
person: person{
first: "James",
last: "Bond",
age: 32,
},
ltk: true,
}
fmt.Println(sa1.first, sa1.last, sa1.age, sa1.ltk)
}
The spec refers to that as an embedded field:
A field declared with a type but no explicit field name is called an embedded field. [...]
struct { T1 // field name is T1 ... }
I'm not sure what you mean by "using one struct type in another struct type" but you are using person
inside secretAgent
by embedding one struct type inside another. The person
fields are also promoted to behave like members of secretAgent
in most cases:
Promoted fields act like ordinary fields of a struct except that they cannot be used as field names in composite literals of the struct.
So you can say:
sa1 := secretAgent{
person: person{
first: "James",
last: "Bond",
age: 32,
},
ltk: true,
}
and
sa1.first
but not:
sa1 := secretAgent{
first: "James",
last: "Bond",
age: 32,
ltk: true,
}
You can also explicitly refer to the embedded person
fields through the person
:
// As a promoted field...
sa1.first
// More explicitly...
sa1.person.first
It is both embedded and nested struct. And you can the naming convention should follow the first word should be upper case.
package main
import "fmt"
type Name struct{
first string
last string
}
type Person struct {
name Name
age int
}
type SecretAgent struct {
person Person
ltk bool
}
func main() {
sa1 := secretAgent{
person: Person{
name: Name {
first: "James",
last: "Bond"
},
age: 32,
},
ltk: true,
}
fmt.Println(sa1.person.first, sa1.person.last, sa1.person.age, sa1.ltk)
}