Home >Backend Development >Golang >How can I access methods of an embedded type in Go when Method Overloading is used?
Method Overloading and Embedded Type Access in Go
In Go, Method Overloading allows for the definition of multiple methods with the same name but different parameters or return types. When a Go struct contains another struct as an embedded type, it raises the question of accessing the methods of the embedded type.
Access Embedded Type Methods
To access the methods of an embedded type:
Example
Consider the following code:
package main import "fmt" 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) } func main() { sam := Employee{Human{"Sam", 45, "111-888-XXXX"}, "Golang Inc"} sam.SayHi() // calls Employee.SayHi sam.Human.SayHi() // calls Human.SayHi }
In this example:
Method Overloading and Embedded Types
When an embedded type's method is overloaded, the child struct has access to all overloads. For example:
package main import "fmt" type A struct { SayHi func(string) } type B struct { A } func main() { a := B{} a.SayHi = func(s string) { fmt.Println("Hello", s) } a.SayHi("World") // prints "Hello World" }
In this example:
The above is the detailed content of How can I access methods of an embedded type in Go when Method Overloading is used?. For more information, please follow other related articles on the PHP Chinese website!