Go Interface as Constraint šŸŽÆ

beginner
22 min

Go Interface as Constraint šŸŽÆ

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!

What is a Go Interface? šŸ“

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.

go
// 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.

Creating a Shape Struct šŸ“

Let's create a Circle and a Rectangle struct that implement the Shape interface.

go
// 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! šŸ’”

Using Interfaces in Practice šŸŽÆ

Let's create a function that calculates the total area of multiple shapes.

go
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:

go
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! šŸŽ‰

Quiz Time šŸ“

Quick Quiz
Question 1 of 1

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! 🄳