In Go, an interface is a type that defines a contract by specifying a set of method signatures. Any type that implements those methods satisfies the interface, allowing for polymorphism

Defining an interface

type shape interface {
	area() float32
	perimeter() float32
}

Define a rect struct

type rect struct {
	width  float32
	height float32
}

Implement the interface

func (r rect) area() float32 {
	return r.width * r.height
}

func (r rect) perimeter() float32 {
	return 2 * (r.width + r.height)
}

Define a square struct

type square struct {
	side float32
}

Implement the shape interface

func (s square) area() float32 {
	return s.side * s.side
}

func (s square) perimeter() float32 {
	return s.side * 4
}

Create a generic function that prints the area and perimeter of a shape

func print(s shape) {
	fmt.Println("area is ", s.area());
}

Call the print function for both the shapes


func main() {
	s := square{side: 10};
	r := rect{width: 20, height: 10}
	
	print(s)
	print(r)
}