Calling Base Type Methods in Embedded Type Overloading
When defining custom types in Go, it's possible to embed one struct within another, allowing for code reuse and inheritance-like functionality. However, this can lead to conflicts when overloading methods.
In the example provided, the Human and Employee structs have overloaded SayHi methods. Is it possible to call the Human method by accessing the embedded type directly?
Yes, this is indeed possible. To access the embedded struct of a parent type, simply use the name of the embedded type as a member of the parent struct. For instance, to call the Human method from the Employee instance:
sam := Employee{Human{"Sam", 45, "111-888-XXXX"}, "Golang Inc"} sam.Human.SayHi()
This will output:
Hi, I am Sam you can call me on 111-888-XXXX
Note that you can also access the parent type's fields directly from the embedded struct. For example, sam.age would access the age field of the Human embedded struct within the Employee struct.
以上是你能用 Go 中的重載方法呼叫嵌入類型中的基底類型方法嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!