In this tutorial, we will cover how interfaces and methods are implemented in the Go programming language. We will also look at how interfaces can be used to achieve polymorphism.
By the end of this tutorial, you will be able to:
- Understand what interfaces are and how to define them
- Implement methods
- Use interfaces to achieve polymorphism
An interface in Go is a type that defines a set of methods. It's a way to specify the behavior of an object. If an object can do this, then it can be used here.
Methods in Go are functions that are associated with a specific type. A method is defined with a receiver, which is similar to this in other languages.
In Go, interfaces are a way to achieve polymorphism. An interface can be implemented by any type, and a variable of an interface type can hold any value that implements those methods.
We'll start by defining an interface named Shape with a method Area.
// Defining our interface
type Shape interface {
Area() float64
}
Next, we'll define two types, Circle and Rectangle, and implement the Area method for both types.
// Circle definition
type Circle struct {
Radius float64
}
// Circle's implementation of the Area method
func (c Circle) Area() float64 {
return math.Pi * c.Radius * c.Radius
}
// Rectangle definition
type Rectangle struct {
Width, Height float64
}
// Rectangle's implementation of the Area method
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
In the above code, Circle and Rectangle now both implement the Shape interface, because they have an Area method.
Now we can use the Shape interface to get the area of any shape.
func printArea(s Shape) {
fmt.Println(s.Area())
}
func main() {
c := Circle{5}
r := Rectangle{3, 4}
printArea(c) // Output: 78.53981633974483
printArea(r) // Output: 12
}
In this tutorial, we've learned about interfaces and methods in Go. We've seen how to define and implement an interface, how to implement methods, and how to use interfaces for polymorphism.
For further learning, you can explore other Go concepts such as slices, maps, and goroutines.
Person interface with Speak method, and implement it for Student and Teacher types.Animal interface with methods Eat and Move, and implement it for Dog and Bird types.Solutions will be provided in the next tutorial. Keep practicing!