首頁 >後端開發 >Golang >你能用 Go 中的重載方法呼叫嵌入類型中的基底類型方法嗎?

你能用 Go 中的重載方法呼叫嵌入類型中的基底類型方法嗎?

Barbara Streisand
Barbara Streisand原創
2024-11-15 10:39:03490瀏覽

Can You Call Base Type Methods in Embedded Types with Overloaded Methods in Go?

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn