To override a method of an embedded struct in Go, you can define a method with the same name and signature in the outer struct.
Here is an example:
package main
import "fmt"
// base struct
type Base struct{}
// method to be overridden
func (b Base) Method() {
fmt.Println("Base method")
}
// struct embedding the Base struct
type Derived struct {
Base
}
// override the Method of the embedded struct
func (d Derived) Method() {
fmt.Println("Override method")
}
func main() {
// create an instance of Derived
d := Derived{}
// call the overridden method
d.Method() // Output: Override method
}
In this example, we have two structs Base
and Derived
. The Derived
struct embeds the Base
struct. By defining the Method
function in the Derived
struct, we are able to override the method of the embedded Base
struct. When calling d.Method()
, it will call the overridden method and print "Override method".