Home > Backend Development > Golang > How Can Go Achieve Inheritance-Like Behavior Through Composition?

How Can Go Achieve Inheritance-Like Behavior Through Composition?

Mary-Kate Olsen
Release: 2024-11-09 15:45:02
Original
741 people have browsed it

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()
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template