首頁 > 後端開發 > Golang > 主體

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

Barbara Streisand
發布: 2024-11-15 10:39:03
原創
392 人瀏覽過

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

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板