What if you could write one piece of code that works with many different things without changing a single line?
Why Interface definition 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 works differently. Without a common way to talk to them, you have to write separate code for each device every time.
Writing separate code for each device is slow and confusing. If you add a new device, you must rewrite or duplicate code. This leads to mistakes and makes your program hard to maintain.
Interfaces let you define a common set of actions that different devices must follow. You write code once using the interface, and any device that implements it can be used interchangeably. This makes your code cleaner and easier to extend.
func printDocument(p Printer) {
p.Print()
}
// Need separate functions for Scanner, Fax, etc.type Device interface {
Execute()
}
func operate(d Device) {
d.Execute()
}
// Any device implementing Execute() can be used hereInterfaces enable writing flexible code that works with many types without changing the core logic.
Think of a music player app that can play songs from different sources: local files, streaming services, or radio. An interface lets the app treat all sources the same way, so you can add new sources easily.
Interfaces define a common set of behaviors for different types.
They reduce code duplication and errors.
They make programs easier to extend and maintain.