Home >Backend Development >Golang >How to Access Embedded Struct Methods When Method Overloading in Go?

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

DDD
DDDOriginal
2024-11-12 14:23:01514browse

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)
}

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

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

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!

Statement:
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