0
0
Goprogramming~3 mins

Why Interface definition in Go? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could write one piece of code that works with many different things without changing a single line?

The Scenario

Imagine you have different types of devices like a printer, scanner, and fax machine. You want to send commands to each device, but each one works differently. Without a common way to talk to them, you have to write separate code for each device every time.

The Problem

Writing separate code for each device is slow and confusing. If you add a new device, you must rewrite or duplicate code. This leads to mistakes and makes your program hard to maintain.

The Solution

Interfaces let you define a common set of actions that different devices must follow. You write code once using the interface, and any device that implements it can be used interchangeably. This makes your code cleaner and easier to extend.

Before vs After
Before
func printDocument(p Printer) {
    p.Print()
}

// Need separate functions for Scanner, Fax, etc.
After
type Device interface {
    Execute()
}

func operate(d Device) {
    d.Execute()
}

// Any device implementing Execute() can be used here
What It Enables

Interfaces enable writing flexible code that works with many types without changing the core logic.

Real Life Example

Think of a music player app that can play songs from different sources: local files, streaming services, or radio. An interface lets the app treat all sources the same way, so you can add new sources easily.

Key Takeaways

Interfaces define a common set of behaviors for different types.

They reduce code duplication and errors.

They make programs easier to extend and maintain.