Golang Method Overriding
In Go, the concept of method overriding is achieved using interfaces rather than through inheritance like in Java. Interfaces define a contract of methods without specifying their implementation.
Implementing Method Overriding in Go:
Using Interfaces:
Example:
// Interface for Get() method type Getter interface { Get() string } // Base type with original implementation type Base struct{} func (base *Base) Get() string { return "base" } // Custom type with overriding implementation type Sub struct { Base } func (sub *Sub) Get() string { return "Sub" }
Advantage:
Alternative Approach using Composition:
Example:
// Sub type with composition type Sub struct { Base custom string } func (sub *Sub) Get() string { // Access the original method via embedded Base if sub.custom == "" { return sub.Base.Get() } return sub.custom }
Advantage:
Note:
The above is the detailed content of How does Go achieve method overriding without traditional inheritance?. For more information, please follow other related articles on the PHP Chinese website!