ProgramGuru

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.

Visual explanation for interface compositionComposed interfaces require every embedded method.Reader: Read()Step 1Writer: Write()Step 2ReadWriter embeds bothStep 3*Note satisfies bothStep 4Composed interfaces require every embedded method.
Composed interfaces require every embedded method.

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

Go

Trace 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 does ReadWriter require?
Choose one answer. You can try again.

Answer and explanation

Both Reader and Writer methods

Correct. ReadWriter requires both Read and Write.

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.

    Next lesson: Polymorphism in Go →