Interfaces in Go
Interfaces are one of the most powerful features of Go. They allow you to define behavior without specifying how that behavior is implemented.
Interfaces make Go programs flexible, modular, and easy to extend, especially in large real-world systems.
What Is an Interface?
An interface is a collection of method signatures. Any type that implements those methods automatically satisfies the interface.
In Go, there is no explicit keyword like implements.
Implementation is implicit.
Defining an Interface
Let’s define an interface that represents a payment method.
type Payment interface {
Pay(amount float64) string
}
This interface says:
- Any type with a
Pay(float64)method satisfies this interface - It does not care how the payment is processed
Implementing an Interface
Now, let’s create a struct that implements this interface.
type CreditCard struct {
CardNumber string
}
Add the required method.
func (c CreditCard) Pay(amount float64) string {
return "Paid ₹" + fmt.Sprintf("%.2f", amount) + " using Credit Card"
}
Now CreditCard automatically implements Payment.
Using Interfaces
You can write functions that work with the interface instead of concrete types.
func processPayment(p Payment, amount float64) {
fmt.Println(p.Pay(amount))
}
Use it in main.
func main() {
card := CreditCard{CardNumber: "1234-5678"}
processPayment(card, 1500)
}
This design allows your system to grow without rewriting existing code.
Multiple Types, Same Interface
Let’s add another payment method.
type UPI struct {
ID string
}
func (u UPI) Pay(amount float64) string {
return "Paid ₹" + fmt.Sprintf("%.2f", amount) + " using UPI"
}
Both CreditCard and UPI now work with the same function.
Why Interfaces Are Powerful
- Loose coupling between components
- Easier testing and mocking
- Cleaner architecture
- Better scalability
Interfaces are heavily used in Go standard libraries and frameworks.
Interface as a Contract
Interfaces define what should be done, not how it should be done.
This is extremely useful in:
- Payment systems
- Logging frameworks
- Database drivers
- Cloud services
The Empty Interface
An empty interface has no methods.
var data interface{}
Every type in Go satisfies the empty interface. It is used when you need to work with values of unknown type.
However, overusing it reduces type safety.
Type Assertion
To extract the concrete value from an interface, use type assertion.
value, ok := data.(string)
Always check the ok value to avoid runtime panics.
Best Practices for Interfaces
- Keep interfaces small
- Define interfaces where they are used
- Prefer behavior-based design
- Avoid unnecessary empty interfaces
What’s Next?
In the next lesson, you will learn about Embedding and Composition in Go, which allows you to build powerful structures without traditional inheritance.