type Shape interface {
Area() float64
}
type Square struct {
Side float64
}
// Receiver this makes struct Square implements interface Shape
func (s Square) Area() float64 {
return s.Side * s.Side
}
func DescribeShape(s Shape) {
fmt.Println("Area:", s.Area())
}
func main() {
sq := Square{Side: 4}
DescribeShape(sq)
}
Summary
Use structs to model data and state.
Use interfaces to define behaviors and enable polymorphism.
Together, they allow for highly reusable and flexible Go code.
func (s Square) Area() float64
is a method declaration in Go. Here's a breakdown of its components:
1. func
Indicates that this is a function.
2. (s Square)
This is called the receiver.
It means the Area method is associated with the type Square.
The receiver provides access to the instance of Square on which the method is called.
Receiver Types:
No comments:
Post a Comment