Home >Backend Development >Golang >How can I access methods of an embedded type in Go when Method Overloading is used?

How can I access methods of an embedded type in Go when Method Overloading is used?

Linda Hamilton
Linda HamiltonOriginal
2024-12-05 18:35:15265browse

How can I access methods of an embedded type in Go when Method Overloading is used?

Method Overloading and Embedded Type Access in Go

In Go, Method Overloading allows for the definition of multiple methods with the same name but different parameters or return types. When a Go struct contains another struct as an embedded type, it raises the question of accessing the methods of the embedded type.

Access Embedded Type Methods

To access the methods of an embedded type:

  1. Declare the embedded type within the parent struct.
  2. Use the name of the embedded type as a member of the parent struct to access its methods.

Example

Consider the following code:

package main

import "fmt"

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

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

In this example:

  • The Human struct is embedded into the Employee struct.
  • The parent struct (Employee) and embedded struct (Human) both have a SayHi() method.
  • To access the SayHi() method of the Human struct, we use sam.Human.SayHi().

Method Overloading and Embedded Types

When an embedded type's method is overloaded, the child struct has access to all overloads. For example:

package main

import "fmt"

type A struct {
    SayHi func(string)
}

type B struct {
    A
}

func main() {
    a := B{}
    
    a.SayHi = func(s string) {
        fmt.Println("Hello", s)
    }
    
    a.SayHi("World") // prints "Hello World"
}

In this example:

  • The A struct has a method named SayHi that takes a string parameter.
  • The B struct embeds A and therefore has access to the SayHi method of A.
  • We can assign a new function to the SayHi method of B, overloading the original SayHi method.

The above is the detailed content of How can I access methods of an embedded type in Go when Method Overloading is used?. 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