Struct Methods
While Go is not an object-oriented language in the traditional sense, it supports methods. A method is simply a function that has a receiver.
Receiver Syntax
The receiver is a special parameter that goes before the function name in parentheses.
type rect struct {
width int
height int
}
// (r rect) is the receiver
func (r rect) area() int {
return r.width * r.height
}
func main() {
myRect := rect{width: 5, height: 10}
fmt.Println(myRect.area()) // 50
}
Conventions
- By convention, the receiver name is usually the first letter of the struct’s name (e.g.,
rforrect). - Methods allow you to encapsulate logic that belongs to a specific type, making your code easier to read and maintain.
Interfaces
Receivers are critical because they allow structs to satisfy interfaces, which is Go’s primary way of achieving polymorphism.