What if you could write code once and use it for many different things without rewriting?
Why Interface use cases 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 manually by writing separate code for each one.
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.
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.
func printDocument(p Printer) {
p.Print()
}
// Need separate functions for Scanner, Fax, etc.type Device interface {
Execute()
}
func useDevice(d Device) {
d.Execute()
}
// Any device implementing Execute() works hereInterfaces enable flexible and reusable code that works with many types without rewriting logic.
A payment system where different payment methods like credit card, PayPal, and bank transfer all implement a common interface to process payments seamlessly.
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.