How to Access Embedded Struct Methods When Method Overloading in Go?

DDD
Release: 2024-11-12 14:23:01
Original
504 people have browsed it

How to Access Embedded Struct Methods When Method Overloading in Go?

The Art of Method Overloading with Embeddings in Go

In the realm of Golang, method overloading allows us to define multiple methods with the same name but different signatures. This concept becomes intriguing when we delve into structured composition using embeddings. Let's explore a question that arises in this context.

Query: Accessing Embedded Struct Methods When Method Overloaded

Consider the following code snippet:

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

Can we invoke the "base" (Human) struct's methods using syntax like sam.Human.SayHi()?

Solution: Embracing Nested Method Invocation

Embeddings in Golang provide a seamless way to access the embedded struct's members within the parent struct. To invoke the Human struct's SayHi method on an Employee instance, we simply use:

sam := Employee{Human{"Sam", 45, "111-888-XXXX"}, "Golang Inc"}
sam.SayHi() // calls Employee.SayHi
sam.Human.SayHi() // calls Human.SayHi
Copy after login

The output:

Hi, I am Sam, I work at Golang Inc. Call me on 111-888-XXXX
Hi, I am Sam you can call me on 111-888-XXXX
Copy after login

Go allows nested method invocations on embedded structs, enabling access to the inherited methods even after method overloading.

The above is the detailed content of How to Access Embedded Struct Methods When Method Overloading 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template