Method သည် type တစ်ခုနဲ့ချိတ်ထားတဲ့ function ပါ။ Struct ထဲ data သိမ်းပြီး method ထဲမှာ behavior ထည့်တာကြောင့် code ကိုပိုစုစည်းနိုင်ပါတယ်။
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) ကို receiver လို့ခေါ်ပါတယ်။ အဲဒါကြောင့် rect.Area() လို object-style ခေါ်နိုင်တာပါ။
You should see
area: 50Info
Method က receiver ကို value copy အဖြစ်ယူနိုင်သလို pointer receiver အဖြစ်လည်းယူနိုင်ပါတယ်။ Data ကိုပြောင်းမယ်ဆို pointer receiver ကိုစဉ်းစားပါ။