What if you could write one code to control many different devices without rewriting everything?
Why Implementing interfaces in Go? - Purpose & Use Cases
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.
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.
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.
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() }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() }You can write one simple code that works with many different types of devices, making your programs easier to grow and change.
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.
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.