content
in python, which is a OOP language, we can define a class with its methods:
class rectangle:
def __init__(self, width, length):
self.width, self.length = width, length
def area(self):
return self.width * self.length
r = rectangle(1, 1)
print(r.area())go is not a object-oriented language, something similar can be achieved with struct method:
type Rectangle struct {
width int
length int
}
func (r Rectangle) area() int {
return r.width * r.length
}
main func() {
rect := Rectangle {1, 1}
fmt.Println(rect.area())
}in the function definition of area, (r rectangle) is called a receiver, which is just a param that goes before function name.
in fact, methods are just functions with receiver arguments → A Tour of Go