Home > Backend Development > Golang > How Can I Access an Embedded Type's Method in Go When It's Overloaded in the Child Struct?

How Can I Access an Embedded Type's Method in Go When It's Overloaded in the Child Struct?

Patricia Arquette
Release: 2024-11-14 22:50:02
Original
917 people have browsed it

How Can I Access an Embedded Type's Method in Go When It's Overloaded in the Child Struct?

Method Overloading in Go: Accessing Embedded Type Methods

When working with structs in Go, it's possible to define methods on both the parent and embedded (nested) structs. However, when a method is overloaded in the child struct, accessing the base struct's method directly may seem impossible.

Overriding Methods with Method Overloading

In the example provided, the Employee struct embeds a Human struct. Both structs define a SayHi() method. However, the Employee struct's SayHi() method overrides the one in the Human struct.

Accessing Embedded Type Methods

To access the embedded struct's method, despite the overloaded method, you can use the following syntax:

parentMember.embeddedMemberName.methodName()
Copy after login

In this case, to call the Human struct's SayHi() method from the Employee struct, you would use:

sam.Human.SayHi()
Copy after login

Code Example

The following example demonstrates accessing the embedded struct's method:

package main

import "fmt"

type Human struct {
    name string
    age int
    phone string
}

func (h *Human) SayHi() {
    fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)
}

type Employee struct {
    Human
    company string
}

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

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

This demonstrates that even when a method is overloaded in a child struct, you can still access the embedded type's method using the syntax described above.

The above is the detailed content of How Can I Access an Embedded Type's Method in Go When It's Overloaded in the Child Struct?. For more information, please follow other related articles on the PHP Chinese website!

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