0
0
Goprogramming~3 mins

Why Implementing interfaces in Go? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could write one code to control many different devices without rewriting everything?

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 has its own way of working. You try to write separate code for each device to handle printing, scanning, or faxing.

The Problem

This manual approach means you write lots of repeated code for each device. If you add a new device, you must rewrite or copy code again. It becomes confusing, hard to maintain, and easy to make mistakes because you forget to update all parts.

The Solution

Interfaces let you define a set of actions (methods) that any device must have. Then, each device just says how it does those actions. Your main code can talk to any device through the interface without worrying about the details. This keeps your code clean, flexible, and easy to extend.

Before vs After
Before
type Printer struct {}
func (p Printer) Print() { /* print code */ }

type Scanner struct {}
func (s Scanner) Scan() { /* scan code */ }

// separate code for each device
func UsePrinter(p Printer) { p.Print() }
func UseScanner(s Scanner) { s.Scan() }
After
type Device interface {
  Operate()
}

type Printer struct {}
func (p Printer) Operate() { /* print code */ }

type Scanner struct {}
func (s Scanner) Operate() { /* scan code */ }

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

You can write one simple code that works with many different types of devices, making your programs easier to grow and change.

Real Life Example

Think about a music app that plays songs from different sources: local files, streaming services, or radio. Using interfaces, the app can play any source without changing its main code.

Key Takeaways

Interfaces define a common set of actions for different types.

They let you write flexible and reusable code.

Adding new types doesn't require changing existing code.