Introduction to Interfaces
Start with Introduction to Interfaces
An interface describes behavior as a set of required methods rather than prescribing a concrete data layout.
What you’ll learn
- Explain the main purpose of introduction to interfaces.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Define type Speaker interface { Speak() string }. A concrete type satisfies this interface when its method set includes Speak with the required signature. There is no implements keyword to write.
An interface value holds a dynamic concrete type and value, allowing code to call a method without knowing all implementation details. Well-sized interfaces usually describe a small behavior used by a caller.
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 Speaker interface{ Speak() string }
type Dog struct{}
func (Dog) Speak() string { return "Woof" }
func announce(s Speaker) { fmt.Println(s.Speak()) }
func main() { announce(Dog{}) }
Output
WoofTrace what the program does
Dog defines the required Speak method, so a Dog value can be passed as a Speaker. announce invokes Speak through the interface and prints Woof.
Avoid common mistakes
- A type does not need to declare that it implements an interface.
- Interface satisfaction depends on the method set and exact method signatures.
Try it yourself
Define a Cat type whose Speak method returns Meow, then pass it to announce.
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 Introduction to 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.