Method Overloading in Go: Accessing Embedded Type Methods
When working with structs in Go, it's possible to define methods on both the parent and embedded (nested) structs. However, when a method is overloaded in the child struct, accessing the base struct's method directly may seem impossible.
Overriding Methods with Method Overloading
In the example provided, the Employee struct embeds a Human struct. Both structs define a SayHi() method. However, the Employee struct's SayHi() method overrides the one in the Human struct.
Accessing Embedded Type Methods
To access the embedded struct's method, despite the overloaded method, you can use the following syntax:
parentMember.embeddedMemberName.methodName()
In this case, to call the Human struct's SayHi() method from the Employee struct, you would use:
sam.Human.SayHi()
Code Example
The following example demonstrates accessing the embedded struct's method:
package main import "fmt" type Human struct { name string age int phone string } func (h *Human) SayHi() { fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone) } type Employee struct { Human company string } 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) } func main() { sam := Employee{Human{"Sam", 45, "111-888-XXXX"}, "Golang Inc"} sam.SayHi() // calls Employee.SayHi() sam.Human.SayHi() // calls Human.SayHi() }
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
This demonstrates that even when a method is overloaded in a child struct, you can still access the embedded type's method using the syntax described above.
The above is the detailed content of How Can I Access an Embedded Type's Method in Go When It's Overloaded in the Child Struct?. For more information, please follow other related articles on the PHP Chinese website!