Interfaces in Go
Go programming language, simply known as Golang, is renowned for its simplicity, efficiency and robustness. Among its major features, Interfaces in Go deserve special attention. They play a significant role in providing a way to define the behavior of objects, making it a powerful tool for handling complex programming structures. If you are a beginner, this tutorial will guide you through understanding and implementing interfaces.
What are Interfaces?
In Go, interfaces are types that define a contract of methods to be implemented by other types. They provide a way to specify the behavior of an object: if something can do this, then it can be used here. Interfaces are declared using the type
keyword, followed by the name of the interface and the keyword interface
. Then, inside curly braces {}
, we list the methods.
Here's an example of a simple interface declaration:
type Shape interface {
Area() float64
}
How to Implement Interfaces
Unlike many other languages, Go does not have a specific keyword to implement interfaces. Instead, a type implements an interface by defining all its methods. In the above example, any type that defines an Area()
method returning a float64
, automatically satisfies the Shape
interface.
Let's see how to implement the Shape
interface with a Rectangle
type:
type Rectangle struct {
Width, Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
Here, Rectangle
defines the Area
method and thus implements the Shape
interface.
Using Interfaces
Interfaces allow us to write functions that can take various types as arguments, as long as they satisfy the interface's contract. Here's how we can write a function that accepts a Shape
:
func printArea(s Shape) {
fmt.Println(s.Area())
}
This function can now be used with any Shape
- whether it's a Rectangle
, a Circle
(if we had one), or any other shape we might define in the future.
r := Rectangle{Width: 10, Height: 5}
printArea(r) // Will print: 50
Empty Interface
Go provides a special type of interface known as the empty interface
. It's defined without any methods, which means all types satisfy the empty interface. It's declared like this:
interface{}
The empty interface is used when we need to handle values of unknown types. It is similar to Object
in Java or object
in C#.
Conclusion
Interfaces in Go provide a flexible and efficient way to handle different types. They offer a way to define behavior for objects, making it easier to design complex programs. Remember, a type implements an interface just by implementing its methods, and there's no need for explicit declaration. With interfaces, you can write code that works with different types, making your Go programs more versatile and robust.