0
0
Goprogramming~3 mins

Why Interface use cases in Go? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could write code once and use it for many different things without rewriting?

The Scenario

Imagine you have different types of devices like a printer, scanner, and fax machine. You want to send commands to each device manually by writing separate code for each one.

The Problem

Writing separate code for each device is slow and error-prone. If you add a new device, you must rewrite or duplicate code everywhere. It becomes hard to manage and easy to make mistakes.

The Solution

Interfaces let you define a common set of actions that all devices must follow. You write code once to work with the interface, and any device that implements it can be used without changing your code.

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

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

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

// Any device implementing Execute() works here
What It Enables

Interfaces enable flexible and reusable code that works with many types without rewriting logic.

Real Life Example

A payment system where different payment methods like credit card, PayPal, and bank transfer all implement a common interface to process payments seamlessly.

Key Takeaways

Manual code for each type is slow and hard to maintain.

Interfaces define shared behavior for many types.

Code using interfaces is simpler, flexible, and reusable.