Method Overriding in Go with Interfaces
Unlike Java, where method overriding involves inheriting and modifying a base class's implementation, Go offers a solution using interfaces.
Interfaces define a set of method signatures that a type must implement. By creating an interface with a method that matches the desired behavior, you can implement it in a new type that can be used in place of the original one.
To achieve this, consider the following example:
type Base struct{} func (base *Base) Get() string { return "base" } func (base *Base) GetName() string { return base.Get() }
To implement method overriding, create an interface:
type Getter interface { Get() string }
Modify the Base type to embed the Getter interface:
type Base struct { Getter }
Now, create a new type that embeds Base and implements the Get method:
type Sub struct { Base } func (sub *Sub) Get() string { return "Sub" }
Finally, modify the GetName method in Base to utilize the Getter interface:
func (base *Base) GetName() string { if g, ok := base.Getter.(Getter); ok { return g.Get() } else { return base.Get() } }
This approach allows you to retain existing consumers of Base while providing the ability to override the Get method in subclasses.
Alternatively, you can also use the following method:
func New() *Sub { userType := &Sub{} userType.Getter = interface{}(userType).(Getter) return userType }
In this case, you must manually set the Getter field in the user code to enable method overriding. Both methods achieve the desired result, but the first approach is considered more idiomatic in Go.
The above is the detailed content of How Can Method Overriding Be Achieved in Go Using Interfaces?. For more information, please follow other related articles on the PHP Chinese website!