search

What is the difference between Go's interface embedding and composition for interfaces in Go?

In Go, interface embedding and composition are two ways to combine multiple interfaces into a single interface.

Interface embedding involves defining a new interface that includes all of the methods of the embedded interfaces. The embedded interfaces are specified in the definition of the new interface using the **interface** keyword followed by the name of the embedded interface, enclosed in parentheses. For example:

type ReaderWriter interface {
    io.Reader
    io.Writer
}

Here, the **ReaderWriter** interface embeds the **io.Reader** and **io.Writer** interfaces.

Interface composition, on the other hand, involves defining a new interface that includes some or all of the methods of one or more existing interfaces, along with additional methods. This is done using the normal interface definition syntax, but including the names of the existing interfaces as types in the definition. For example:

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

Here, the **ReaderWriter** interface includes the **Read** and **Write** methods from the **io.Reader** and **io.Writer** interfaces, as well as an additional **Close** method.

In summary, interface embedding is a way to create a new interface that includes all of the methods of one or more existing interfaces, while interface composition is a way to create a new interface that includes some or all of the methods of one or more existing interfaces, along with additional methods.

Related Questions You Might Be Interested