How to Embed Interface in Go: Syntax and Examples
In Go, you embed an interface by including it as a field without a name inside another interface using
interface embedding. This allows the new interface to inherit all methods of the embedded interface, enabling easy composition and reuse.Syntax
To embed an interface in Go, simply list the interface name inside another interface without a field name. This means the new interface inherits all methods of the embedded interface.
- InterfaceName: The name of the interface you want to embed.
- NewInterface: The interface that embeds the other interface.
go
type Reader interface { Read(p []byte) (n int, err error) } type Writer interface { Write(p []byte) (n int, err error) } type ReadWriter interface { Reader Writer }
Example
This example shows how ReadWriter embeds Reader and Writer interfaces. Any type implementing both Read and Write methods satisfies ReadWriter.
go
package main import ( "fmt" ) type Reader interface { Read(p []byte) (n int, err error) } type Writer interface { Write(p []byte) (n int, err error) } type ReadWriter interface { Reader Writer } type MyBuffer struct { data []byte } func (b *MyBuffer) Read(p []byte) (int, error) { n := copy(p, b.data) b.data = b.data[n:] return n, nil } func (b *MyBuffer) Write(p []byte) (int, error) { b.data = append(b.data, p...) return len(p), nil } func main() { var rw ReadWriter = &MyBuffer{} rw.Write([]byte("Hello ")) rw.Write([]byte("World!")) buf := make([]byte, 12) n, _ := rw.Read(buf) fmt.Println(string(buf[:n])) }
Output
Hello World!
Common Pitfalls
Common mistakes when embedding interfaces include:
- Forgetting to embed the interface by name only (adding a field name breaks embedding).
- Assuming embedding copies methods instead of composing them.
- Not implementing all embedded interface methods in the concrete type.
Embedding interfaces means the new interface requires all methods from embedded interfaces, not just some.
go
/* Wrong: embedding with a field name disables embedding */ type Wrong interface { r Reader // This is a field, not embedding } /* Correct: embed by interface name only */ type Correct interface { Reader }
Quick Reference
- Embed interfaces by listing their names inside another interface without field names.
- Embedded interfaces' methods become part of the new interface.
- Concrete types must implement all methods from embedded interfaces.
- Embedding helps compose complex interfaces from simpler ones.
Key Takeaways
Embed interfaces by listing interface names without field names inside another interface.
Embedded interfaces' methods are combined into the new interface automatically.
Concrete types must implement all methods from all embedded interfaces to satisfy the new interface.
Embedding interfaces helps build complex interfaces by reusing simpler ones.
Avoid naming embedded interfaces as fields to ensure proper embedding.