Home > Backend Development > Golang > Can You Call Base Type Methods in Embedded Types with Overloaded Methods in Go?

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

Barbara Streisand
Release: 2024-11-15 10:39:03
Original
501 people have browsed it

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()
Copy after login

This will output:

Hi, I am Sam you can call me on 111-888-XXXX
Copy after login

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.

The above is the detailed content of Can You Call Base Type Methods in Embedded Types with Overloaded Methods in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template