Golang / GoLang Interfaces and Object Oriented Interview Questions
How does interface embedding (composition) work in Go?
Go interfaces can embed other interfaces. The composed interface's method set is the union of all embedded interface method sets. This is Go's primary mechanism for building larger interface contracts from smaller, focused ones — following the Interface Segregation Principle.
// Small, focused interfaces (the Go standard library style) type Reader interface { Read(p []byte) (n int, err error) } type Writer interface { Write(p []byte) (n int, err error) } type Closer interface { Close() error } // Composed interfaces type ReadWriter interface { Reader // embeds Reader Writer // embeds Writer } type ReadWriteCloser interface { Reader Writer Closer } // *os.File satisfies all of the above var f *os.File = os.Stdout var rw ReadWriter = f // *os.File has Read + Write var rwc ReadWriteCloser = f // *os.File has Read + Write + Close var r Reader = rw // ReadWriter is assignable to Reader // Your composed interface type DataStore interface { Reader Writer Flush() error Stats() map[string]int64 } // Any type with Read, Write, Flush, Stats satisfies DataStore // without knowing anything about DataStore
Design principle: prefer many small interfaces over one large interface. Small interfaces (io.Reader has 1 method, io.Writer has 1 method) are easy to satisfy and easy to mock in tests. Accept interfaces in your functions; return concrete types from constructors. The idiomatic Go proverb: "The bigger the interface, the weaker the abstraction."
More Related questions...