search

Explain the use of Go's interface embedding for data reuse and composition?

In Go, interface embedding allows you to embed one or more interfaces into another interface, allowing the composite interface to inherit the methods of the embedded interfaces. This is useful for data reuse and composition, as it allows you to create new interfaces that are composed of existing interfaces.

Here is an example:

type Reader interface {
    Read(p []byte) (n int, err error)
}

type Closer interface {
    Close() error
}

type ReadCloser interface {
    Reader
    Closer
}

In this example, we have defined three interfaces: **Reader**, **Closer**, and **ReadCloser**. **Reader** and **Closer** are two existing interfaces, and **ReadCloser** is a new interface that is composed of both **Reader** and **Closer** through interface embedding.

Now, any type that implements both **Reader** and **Closer** will automatically implement **ReadCloser**, since it inherits the methods from both embedded interfaces.

type MyReaderCloser struct {
    // implementation details
}

func (mrc *MyReaderCloser) Read(p []byte) (n int, err error) {
    // implementation details
}

func (mrc *MyReaderCloser) Close() error {
    // implementation details
}

var myRC ReadCloser = &MyReaderCloser{}

In this example, **MyReaderCloser** implements both **Reader** and **Closer**, so it automatically implements **ReadCloser** through interface embedding. We can then create a **ReadCloser** variable and assign it to an instance of **MyReaderCloser**.

Related Questions You Might Be Interested