Understanding Interfaces in Golang
In Go, interfaces are a powerful feature that allows you to define a set of methods that a type must implement. Interfaces enable polymorphism, allowing different types to be treated in a similar way, making your code more flexible and reusable.
Defining an Interface
An interface in Go is a type that specifies a set of method signatures. Any type that implements these methods is said to “satisfy” the interface.
type Shape interface {
Area() float64
Perimeter() float64
}Here, Shape is an interface that requires any type implementing it to have both Area() and Perimeter() methods.
Implementing Interfaces
There is no explicit keyword like “implements” in Go. A type satisfies an interface by simply implementing its methods.
type Circle struct {
Radius float64
}
func (c Circle) Area() float64 {
return 3.14 * c.Radius * c.Radius
}
func (c Circle) Perimeter() float64 {
return 2 * 3.14 * c.Radius
}Get Hanu Tyagi’s stories in your inbox
Join Medium for free to get updates from this writer.
The Circle type implements the Shape interface because it defines both Area() and Perimeter() methods.
Practical Use Case
Interfaces shine in scenarios where you want to handle different types that share common behavior without knowing their exact implementation. For instance, let’s say we want to calculate the total area of different shapes:
func totalArea(shapes []Shape) float64 {
var total float64
for _, shape := range shapes {
total += shape.Area()
}
return total
}
func main() {
circle := Circle{Radius: 5}
shapes := []Shape{circle}
fmt.Println("Total Area:", totalArea(shapes))
}Here, totalArea can work with any type that implements the Shape interface, making it versatile and extendable.
Use Cases in Real-World Applications
- Database Access: Interfaces can abstract different database drivers, allowing the same code to work with MySQL, PostgreSQL, or any other DB driver by implementing the same methods (e.g.,
Query,Execute). - Testing: Interfaces help in writing mock objects for unit tests. For instance, you could mock a
PaymentProcessorinterface to test how your system handles different payment gateways without interacting with actual external services. - HTTP Handlers: In Go’s standard library, the
http.Handlerinterface is widely used to handle HTTP requests, allowing different types to implement custom request handling logic.
Interfaces in Go allow you to design flexible, decoupled systems by focusing on behavior rather than concrete types. This promotes clean, maintainable code that can easily adapt to changes or extensions.






