Home  >  Article  >  Backend Development  >  How do I override an embedded struct\'s method in Go?

How do I override an embedded struct\'s method in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-26 14:08:31302browse

How do I override an embedded struct's method in Go?

Overriding Embedded Struct Methods in Go

When embeding a struct in Go, the embedded struct's methods become available as top-level members of the embedding struct. This allows for easy access to the embedded struct's functionality. However, if the embedding struct implements its own method with the same name, the embedded struct's method will be hidden.

Consider the following example:

<code class="go">package main

import "fmt"

type Base struct {
    val int
}
func (b *Base)Set(i int) {
    b.val = i
}
type Sub struct {
    Base
    changed bool
}

func (b *Sub)Set(i int) {
    b.val = i
    b.changed = true
}
func main() {
    s := &Sub{}
    s.Base.Set(1)
    var b *Base = &s.Base
    fmt.Printf("%+v\n", b)
    fmt.Printf("%+v\n", s)
}</code>

In this example, the Sub struct embeds the Base struct. The Base struct has a Set method, which is hidden by the Sub struct's own Set method. When s.Base.Set(1) is called, the Base struct's Set method is invoked, not the Sub struct's Set method.

To override the embedded struct's method in the embedding struct, you can simply call the embedded struct's method from within the embedding struct's method. For example, the following code would override the Base struct's Set method in the Sub struct:

<code class="go">func (b *Sub)Set(i int) {
    b.Base.Set(i)
    b.changed = true
}</code>

With this change, when s.Set(1) is called, the Sub struct's Set method will be invoked, which will call the Base struct's Set method and also set the changed field to true. This allows you to override the behavior of the embedded struct's method while still having access to the embedded struct's functionality.

The above is the detailed content of How do I override an embedded struct\'s method 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