Home >Backend Development >Golang >How Can Go Achieve Inheritance-Like Behavior Through Composition?
Go Inheritance: Alternative Approach
While Go emphasizes composition over inheritance, it offers mechanisms for achieving similar functionality. To provide a reusable base struct with methods that can be extended, a common strategy is to utilize embedding.
Instead of relying on parent struct methods, embedded structs provide access to their own methods within the context of the enclosing struct. Here's how it works:
// Define narrow interfaces type MyReader interface { Read() } type MyWriter interface { Write() } // Create a composite interface type MyReadWriter interface { MyReader MyWriter } // Create structs implementing the interfaces type ReaderStruct struct {} func (r *ReaderStruct) Read() {} type WriterStruct struct {} func (w *WriterStruct) Write() {} // Embed the structs into a composite struct type ReadWriterStruct struct { *ReaderStruct *WriterStruct } func (rw *ReadWriterStruct) DoStuff() { rw.Read() rw.Write() } func main() { rw := &ReadWriterStruct{} rw.DoStuff() }
In this example, the ReadWriterStruct can act as both a Reader and a Writer due to embedding. By composing structs instead of inheriting from them, Go promotes modularity and better encapsulation of functionality.
The above is the detailed content of How Can Go Achieve Inheritance-Like Behavior Through Composition?. For more information, please follow other related articles on the PHP Chinese website!