Interface Composition
Start with Interface Composition
You can compose interfaces by embedding smaller interfaces to describe an object that supports several behaviors.
What you’ll learn
- Explain the main purpose of interface composition.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
For example, ReadWriter can embed separate Reader and Writer interfaces. A type satisfies the composition only when it provides every required method.
This allows consumers to ask for exactly the capabilities they need: one function may accept only Reader, while another accepts ReadWriter. Embedding an interface merges method requirements; it does not contain or allocate a concrete object.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
type Reader interface{ Read() string }
type Writer interface{ Write(string) }
type ReadWriter interface {
Reader
Writer
}
type Note struct{ Text string }
func (n *Note) Read() string { return n.Text }
func (n *Note) Write(s string) { n.Text = s }
func update(rw ReadWriter) {
rw.Write("Go")
fmt.Println(rw.Read())
}
func main() { update(&Note{}) }
Output
GoTrace what the program does
ReadWriter requires both Read and Write. The *Note type has the two pointer-receiver methods, so &Note{} satisfies it and update writes then prints Go.
Avoid common mistakes
- Embedding interfaces combines method requirements, not data fields.
- A type missing any required method does not satisfy the composed interface.
Try it yourself
Create a method that accepts Reader only and call it with a pointer to Note.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Interface Composition in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.