0
0
Goprogramming~3 mins

Why interfaces are used in Go - The Real Reasons

Choose your learning style9 modes available
The Big Idea

What if you could write one code that works for many different things without changing it?

The Scenario

Imagine you have different types of devices like a phone, a tablet, and a laptop. Each device can perform actions like turning on or off, but each does it in its own way. If you write separate code for each device every time you want to turn it on, your code becomes messy and hard to manage.

The Problem

Writing separate code for each device means repeating yourself a lot. It's easy to make mistakes, and if you add a new device, you have to change many parts of your code. This slow process makes your program hard to grow and fix.

The Solution

Interfaces let you define a set of actions that any device can do without worrying about how they do it. You write one piece of code that works with any device that follows the interface. This keeps your code clean, flexible, and easy to update.

Before vs After
Before
phone.TurnOn()
tablet.TurnOn()
laptop.TurnOn()
After
var device Device
device.TurnOn()
What It Enables

Interfaces let your program work with many different types in a simple, unified way, making your code easier to extend and maintain.

Real Life Example

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

Key Takeaways

Interfaces define common actions without fixing how they are done.

They reduce repeated code and errors.

They make programs flexible and easier to grow.