Home > Article > Backend Development > Go and Inheritance: When Does Composition Outshine Inheritance for Code Reusability?
In Go, extending functionality beyond base structures is often approached using composition instead of inheritance. This ensures code clarity and minimizes duplication.
Consider the following example where the goal is to define a base struct with methods that can be extended by other structs:
type MyInterface interface { SomeMethod(string) OtherMethod(string) } type Base struct { B MyInterface } func (b *Base) SomeMethod(x string) { b.B.OtherMethod(x) } type Extender struct { Base } func (b *Extender) OtherMethod(x string) { // Do something... } func NewExtender() *Extender { e := Extender{} e.Base.B = &e return &e }
While this example works, it appears convoluted due to its cyclical structure. To reduce code duplication and create more readable code, consider using embedding.
Embedding allows you to compose structs that implement specific interfaces. For instance, you could create narrow interfaces for reading and writing:
type Reader interface { Read(p []byte) (n int, err error) } type Writer interface { Write(p []byte) (n int, err error) }
By composing these interfaces, you can create a ReadWriter interface:
type ReadWriter interface { Reader Writer }
Similarly, you can compose structs that implement Reader and Writer into a MyReadWriter struct:
type MyReader struct {} func (r *MyReader) Read(p []byte) (n int, err error) { // Implements Reader interface. } type MyWriter struct {} func (w *MyWriter) Write(p []byte) (n int, err error) { // Implements Writer interface. } type MyReadWriter struct { *MyReader *MyWriter }
The MyReadWriter struct now implements the ReadWriter interface, allowing you to use any component that implements Reader or Writer within this struct.
This embedding technique promotes code reusability, dependency injection, and facilitates testing by enabling the swapping of components that implement specific interfaces.
The above is the detailed content of Go and Inheritance: When Does Composition Outshine Inheritance for Code Reusability?. For more information, please follow other related articles on the PHP Chinese website!