How to use interfaces in go?
Here's an example of how to use Go's interfaces:
package main
import (
"fmt"
)
// Define an interface with a single method
type Shape interface {
Area() float64
}
// Define a struct that implements the Shape interface
type Rectangle struct {
Width float64
Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
// Define another struct that implements the Shape interface
type Circle struct {
Radius float64
}
func (c Circle) Area() float64 {
return 3.14 * c.Radius * c.Radius
}
func main() {
// Create instances of the Rectangle and Circle structs
r := Rectangle{Width: 10, Height: 5}
c := Circle{Radius: 7}
// Create a slice of Shape objects and add the Rectangle and Circle objects to it
shapes := []Shape{r, c}
// Iterate over the slice and print out the area of each shape
for _, shape := range shapes {
fmt.Println("Area:", shape.Area())
}
}
In this example, we define an interface called **Shape**
with a single method called **Area()**
. We then define two structs, **Rectangle**
and **Circle**
, that both implement the **Shape**
interface by providing their own **Area()**
methods.
In the **main()**
function, we create instances of the **Rectangle**
and **Circle**
structs and add them to a slice of **Shape**
objects. We then iterate over the slice and call the **Area()**
method on each shape, which prints out the area of the rectangle and circle.
By using interfaces, we can write generic code that can work with any type that implements the interface. This can make our code more flexible and easier to reuse.