Home  >  Article  >  Backend Development  >  How to Override Embedded Struct Methods in Go Without Affecting the Base Struct?

How to Override Embedded Struct Methods in Go Without Affecting the Base Struct?

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 03:01:03269browse

How to Override Embedded Struct Methods in Go Without Affecting the Base Struct?

Overriding Embedded Struct Methods in Go

In Go, embedded structs inherit the fields and methods of their base structs. However, a conflict can arise when both the base and embedded structs implement a method with the same name. This article explores a solution to override the embedded struct's method without affecting the base struct.

Consider the following code:

<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

    // Both print the same value
    fmt.Printf("%+v\n", b)
    fmt.Printf("%+v\n", s)
}</code>

Here, the Sub type embeds the Base type. Both Sub and Base have a method named Set, and when you call s.Base.Set(), you are bypassing the Sub.Set() method and directly calling the Base.Set() method.

To override the embedded struct's method, you can call the Sub.Set() method instead. In Go, when a type implements a method with the same name as its embedded type, the embedded method is hidden.

Here's an updated version of the code:

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

func main() {
    s := &Sub{}
    s.Set(1)
    var b *Base = &s.Base

    // Note: b.val is now 1
    // s.changed is now true
    fmt.Printf("%+v\n", b)
    fmt.Printf("%+v\n", s)
}</code>

In this example, when you call s.Set(1), the Sub.Set() method will be invoked, which in turn calls the Base.Set() method. This updates the val field of the Base struct embedded in Sub. The changed field will also be set to true to indicate that the value has been modified.

This solution allows you to override the embedded struct's method without affecting the base struct. It is a common technique used in Go to achieve code reusability and flexibility.

The above is the detailed content of How to Override Embedded Struct Methods in Go Without Affecting the Base Struct?. 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