Home  >  Article  >  Backend Development  >  How Can You Override Embedded Struct Methods in Golang?

How Can You Override Embedded Struct Methods in Golang?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-27 08:55:30798browse

How Can You Override Embedded Struct Methods in Golang?

Overriding Embedded Struct Methods in Golang

In Golang, when a struct embeds another struct (referred to as embedding), the embedded struct's fields and methods become directly accessible to the embedding struct. However, if the embedding struct redefines a method from the embedded struct, it can override the original method.

Consider the following code:

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

We have embedded Base into Sub. Now, if we try to access Base's Set method from Sub, it will be hidden by Sub's own Set method:

<code class="go">func t16() {
    s := &Sub{}
    // This calls Base's Set method
    s.Base.Set(1) 
    // This causes an error, as s.Set hides Base's Set
    s.Set(10) 
}</code>

To override this behavior, we can redefine Sub's Set method to call Base's Set method explicitly:

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

Now, when we call s.Set(), it will invoke Base's Set method while still allowing us to track changes in Sub.

<code class="go">func t16() {
    s := &Sub{}
    // Calls Sub's overridden Set method
    s.Set(10) 
    fmt.Printf("%+v\n", s) // Output: {Base:{val:10} changed:true}
}</code>

This method allows you to override the embedded struct's methods while maintaining access to the original method through the embedded struct field.

The above is the detailed content of How Can You Override Embedded Struct Methods in Golang?. 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