Implementing Interfaces
Start with Implementing Interfaces
Go checks interface implementation implicitly, based on the methods a concrete type provides.
What you’ll learn
- Explain the main purpose of implementing interfaces.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
A single function accepting an interface can work with many concrete types. Assigning a value to an interface variable is allowed only when the value type’s method set satisfies the interface.
For methods with pointer receivers, a pointer to the concrete type may implement an interface even when the non-pointer value does not. You can use a compile-time assertion such as var _ Writer = (*Buffer)(nil) when that check adds clarity.
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 Describer interface{ Describe() string }
type Book struct{ Title string }
type Film struct{ Title string }
func (b Book) Describe() string { return "Book: " + b.Title }
func (f Film) Describe() string { return "Film: " + f.Title }
func show(d Describer) { fmt.Println(d.Describe()) }
func main() {
show(Book{Title: "Go Basics"})
show(Film{Title: "A Journey"})
}
Output
Book: Go Basics
Film: A JourneyTrace what the program does
Book and Film independently implement Describe with the same signature. The show function accepts either as a Describer and calls the correct implementation.
Avoid common mistakes
- A matching method name with different parameters or results is not sufficient.
- Interface implementation does not require explicit registration or subclassing.
Try it yourself
Add a Podcast type with a Describe method and pass it to show.
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 Implementing Interfaces 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.