To avoid naming conflicts when embedding structs with the same field names in Go, you can use field name promotion and fully qualified identifiers. Here are a few ways to handle naming conflicts:
Field Name Promotion:
type Outer struct {
Inner // Embedded struct
Field1 string
}
type Inner struct {
Field1 int
}
func main() {
o := Outer{
Inner: Inner{Field1: 42},
Field1: "Hello",
}
fmt.Println(o.Field1) // Output: Hello
fmt.Println(o.Inner.Field1) // Output: 42
}
Fully Qualified Identifiers:
type Outer struct {
Inner // Embedded struct
Field1 string
}
type Inner struct {
Field1 int
}
func main() {
o := Outer{
Inner: Inner{Field1: 42},
Field1: "Hello",
}
fmt.Println(o.Field1) // Output: Hello
fmt.Println(o.Inner.Field1) // Output: 42
fmt.Println(o.Inner.Field1) // Output: 42
}
By using field name promotion and fully qualified identifiers, you can avoid naming conflicts when embedding structs with the same field names in Go.