Can I Access Base Struct Methods in Go When Subtyping?

Barbara Streisand
Release: 2024-11-12 02:43:01
Original
864 people have browsed it

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

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

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template