Document Details

Methods

Receiver

<aside> 💡 In general, all methods on a given type should have either value or pointer receivers, but not a mixture of both.

</aside>


Interfaces

It defines a set of method signatures (names, input parameters, and return types) that a type must implement to satisfy the interface.

type Shape interface {
    Area() float64
    Perimeter() float64
}

This declares a Shape interface with two methods: Area() and Perimeter(). Any type that wants to be considered a "shape" must implement both of these methods.

type Rectangle struct {
    width, height float64
}

func (r Rectangle) Area() float64 {
    return r.width * r.height
}

func (r Rectangle) Perimeter() float64 {
    return 2*r.width + 2*r.height
}
// ... similar implementations for Circle, Triangle, etc.
func PrintShapeInfo(s Shape) {
    fmt.Println("Area:", s.Area())
    fmt.Println("Perimeter:", s.Perimeter())
}

rect := Rectangle{width: 5, height: 10}
PrintShapeInfo(rect)