0
0
Goprogramming~3 mins

Why Interface satisfaction in Go? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could write one program that works with any device 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 a command to each device to start working, but each device has its own way of doing it. You try to write separate code for each device every time you want to use them.

The Problem

This manual way means you write a lot of repeated code. It becomes hard to manage and easy to make mistakes. If you add a new device, you must change many parts of your program. It's slow and confusing.

The Solution

Interface satisfaction lets you define a common set of actions (methods) that any device must have. Then, any device that has those actions automatically fits the interface. You can write one simple code that works with all devices without changing it when you add new ones.

Before vs After
Before
if device == "printer" {
    printerPrint()
} else if device == "scanner" {
    scannerScan()
}
After
type Device interface {
    Start()
}

func UseDevice(d Device) {
    d.Start()
}
What It Enables

You can write flexible and clean programs that easily work with many different types without rewriting code.

Real Life Example

Think of a music app that plays songs from different sources: local files, streaming services, or radio. Each source can be different, but if they all satisfy a Player interface, the app can play any source the same way.

Key Takeaways

Interfaces define a common set of actions for different types.

Any type that has those actions automatically fits the interface.

This makes code simpler, flexible, and easier to extend.