Home >Backend Development >Golang >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!