Home >Backend Development >Golang >Can I Access Base Struct Methods in Go When Subtyping?

Can I Access Base Struct Methods in Go When Subtyping?

Barbara Streisand
Barbara StreisandOriginal
2024-11-12 02:43:01913browse

Can I Access Base Struct Methods in Go When Subtyping?

Method Overloading and Subtyping in Go structs

Consider the following Go code:

package main

import "fmt"

type Human struct {
    name string
    age int
    phone string
}


type Employee struct {
    Human // Embedding
    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()
}

This code demonstrates method overloading, where the SayHi method is defined in both the Human and Employee structs. When a method is invoked on a variable of the Employee type, the method in the Employee struct is called.

Accessing Base Struct Methods

One may wonder if it's possible to invoke the SayHi method defined in the Human struct on an Employee instance. In Go, accessing the base struct's methods is straightforward. To do this, refer to the embedded type using the struct member's name, as shown below:

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

This code demonstrates that accessing the embedded struct's method can be done seamlessly. The output would be:

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

The above is the detailed content of Can I Access Base Struct Methods in Go When Subtyping?. 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