In Go, embedding an anonymous struct (struct literal) is similar to embedding named structs. Here's an example of how to do it:
package main
import "fmt"
type Person struct {
name string
age int
// Embedding an anonymous struct
contact struct {
email string
address string
}
}
func main() {
p := Person{
name: "John Doe",
age: 30,
contact: struct {
email string
address string
}{
email: "[email protected]",
address: "123 Main St",
},
}
fmt.Println(p.name)
fmt.Println(p.contact.email)
fmt.Println(p.contact.address)
}
In the above example, the Person
struct embeds an anonymous struct using the contact
field. The anonymous struct has two fields: email
and address
.
While initializing a Person
struct, we also initialize the anonymous struct using its field names and values.
Note that anonymous structs are useful when you want to embed a small, unrelated struct directly into another struct without the need to define it separately.