Compose and embed interfaces
Compose and embed interfaces
An interface may embed another interface by naming it inside its declaration. A basic composed interface requires every method from its embedded interfaces. This lets a consumer request multiple capabilities without repeating signatures.
package main
import ( "fmt")
type Reader interface{ Read() string }type Writer interface{ Write(string) }type Store interface { Reader Writer}type Memory struct{ Text string }
func (m *Memory) Read() string { return m.Text }func (m *Memory) Write(s string) { m.Text = s }func main() { var s Store = &Memory{} s.Write("hello") fmt.Println(s.Read())}Store requires both Read and Write. These are illustrative custom interfaces, not io.Reader or io.Writer, which have different signatures. *Memory satisfies both and therefore Store.
Expected output:
helloPass a narrower capability
package main
import ( "fmt")
type Named interface{ Name() string }type Sized interface{ Size() int }type Item interface { Named Sized}type Box struct{}
func (Box) Name() string { return "box" }func (Box) Size() int { return 3 }func label(n Named) string { return n.Name() }func main() { var i Item = Box{} fmt.Println(label(i), i.Size())}Every Item provides Named, so passing i to label is allowed. Embedded methods with the same name must have identical signatures. Interfaces containing type terms such as ~int are non-basic and can only be used as constraints (or within other constraint interfaces), not ordinary variable types; generics are taught later.
Expected output:
box 3Try it locally
Compose Opener with Open() and Closer with Close() into Resource. Implement both on a type and call them through Resource, printing open and close on separate lines.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Interfaces 03: Compose and embed interfaces
Check the lesson objective before moving on.
Which methods must a type provide for interface{Reader;Writer}?
Can interface{~int} be used as an ordinary variable type?