What is Interface in Go: Simple Explanation and Example
interface is a type that defines a set of method signatures but does not implement them. It allows different types to be treated the same way if they implement those methods, enabling flexible and reusable code.How It Works
Think of an interface in Go like a contract or a promise. It says, "Any type that wants to be considered this interface must have these specific methods." However, the interface itself does not say how these methods work, just that they must exist.
This is similar to how in real life, a remote control works with any TV that follows the same button layout. The remote doesn't care about the TV brand, only that the TV responds to the buttons it sends. In Go, if a type has the methods an interface requires, it automatically "implements" that interface without extra code.
Example
This example shows an interface Speaker with one method Speak(). Two types, Dog and Cat, implement this method. A function SaySomething accepts any Speaker and calls Speak(), demonstrating how interfaces allow different types to be used interchangeably.
package main import "fmt" type Speaker interface { Speak() } type Dog struct {} func (d Dog) Speak() { fmt.Println("Woof!") } type Cat struct {} func (c Cat) Speak() { fmt.Println("Meow!") } func SaySomething(s Speaker) { s.Speak() } func main() { dog := Dog{} cat := Cat{} SaySomething(dog) SaySomething(cat) }
When to Use
Use interfaces in Go when you want to write flexible code that can work with different types in a uniform way. They are especially useful for:
- Designing functions or methods that can accept any type that meets certain behavior.
- Decoupling code so that implementations can change without affecting the rest of the program.
- Writing tests by creating mock types that implement interfaces.
For example, if you write a logging system, you can define an interface for logging behavior and then use different loggers (console, file, network) without changing the main code.
Key Points
- An interface defines method signatures without implementations.
- Any type with those methods automatically implements the interface.
- Interfaces enable polymorphism and flexible code design.
- They help separate what something does from how it does it.