Home >Backend Development >Golang >How to Access Embedded Struct Methods When Method Overloading in Go?
In the realm of Golang, method overloading allows us to define multiple methods with the same name but different signatures. This concept becomes intriguing when we delve into structured composition using embeddings. Let's explore a question that arises in this context.
Consider the following code snippet:
type Human struct { name string age int phone string } type Employee struct { Human company string } func (h *Human) SayHi() { fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone) } func (e *Employee) SayHi() { fmt.Printf("Hi, I am %s, I work at %s. Call me on %s\n", e.name, e.company, e.phone) }
Can we invoke the "base" (Human) struct's methods using syntax like sam.Human.SayHi()?
Embeddings in Golang provide a seamless way to access the embedded struct's members within the parent struct. To invoke the Human struct's SayHi method on an Employee instance, we simply use:
sam := Employee{Human{"Sam", 45, "111-888-XXXX"}, "Golang Inc"} sam.SayHi() // calls Employee.SayHi sam.Human.SayHi() // calls Human.SayHi
The output:
Hi, I am Sam, I work at Golang Inc. Call me on 111-888-XXXX Hi, I am Sam you can call me on 111-888-XXXX
Go allows nested method invocations on embedded structs, enabling access to the inherited methods even after method overloading.
The above is the detailed content of How to Access Embedded Struct Methods When Method Overloading in Go?. For more information, please follow other related articles on the PHP Chinese website!