Welcome to our deep dive into Go Interfaces! In this lesson, we'll explore how Go Interfaces can act as a powerful tool to shape your code into a more flexible, reusable, and maintainable form. Let's get started!
In simple terms, an interface in Go is a contract that defines a set of methods and their signatures. A type (either a struct, function, pointer, or interface) implements an interface if it provides all the methods with the matching signatures.
// This is an interface
type Shape interface {
Area() float64
}š” Pro Tip: Interfaces in Go allow for polymorphism, which means we can treat different types as if they are of the same type, as long as they implement the same interface.
Let's create a Circle and a Rectangle struct that implement the Shape interface.
// Circle struct
type Circle struct {
radius float64
}
// Rectangle struct
type Rectangle struct {
width, height float64
}
// Implementing the Area() method for Circle
func (c Circle) Area() float64 {
return 3.14 * c.radius * c.radius
}
// Implementing the Area() method for Rectangle
func (r Rectangle) Area() float64 {
return r.width * r.height
}Now, both Circle and Rectangle types can be used interchangeably with any code expecting a Shape interface. This is the power of interfaces! š”
Let's create a function that calculates the total area of multiple shapes.
func TotalArea(shapes []Shape) float64 {
totalArea := 0.0
for _, shape := range shapes {
totalArea += shape.Area()
}
return totalArea
}Now you can call TotalArea with a mix of Circle and Rectangle objects:
circle1 := Circle{radius: 5.0}
rectangle1 := Rectangle{width: 4.0, height: 6.0}
shapes := []Shape{circle1, rectangle1}
area := TotalArea(shapes)
fmt.Println("Total Area:", area)Run the code, and you'll see the total area of the circle1 and rectangle1 objects, calculated using the TotalArea function! š
Which of the following types can be passed to the `TotalArea` function?
We've just scratched the surface of Go Interfaces! In the next sections, we'll explore methods with receiver types, interfaces as types, interface embedding, and more. So stay tuned! š
Happy coding! š„³