Method is a function tied to a type. Storing data in a struct and putting behavior in methods lets you keep your code more organized.
go
package main
import "fmt"
type Rectangle struct {
Width int
Height int
}
func (r Rectangle) Area() int {
return r.Width * r.Height
}
func main() {
rect := Rectangle{Width: 10, Height: 5}
fmt.Println("area:", rect.Area())
}func (r Rectangle) Area(), (r Rectangle) is called the receiver — which is why you can call rect.Area() in an object-style way.
You should see
area: 50Info
A method can take its receiver either as a value copy or as a pointer receiver. If you want to modify the underlying data, consider using a pointer receiver.