Methods
Go has no class keyword. Instead, you attach functions to types with a receiver.
Methods
A method is a function with an extra parameter before its name — the receiver — that determines which type it's attached to:
type Rectangle struct {
Width, Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
rect := Rectangle{Width: 3, Height: 4}
fmt.Println(rect.Area()) // 12(r Rectangle) is the receiver — read it as "this method is attached to Rectangle, and inside the method, the receiving value is called r." Calling rect.Area() is just Area(rect) with nicer syntax.
Value receivers vs. pointer receivers
Just like passing a struct to a plain function, a value receiver ((r Rectangle)) gets a copy — fine for reading, useless for mutating. A pointer receiver ((r *Rectangle)) can modify the original:
func (r *Rectangle) Scale(factor float64) {
r.Width *= factor
r.Height *= factor
}
rect := Rectangle{Width: 3, Height: 4}
rect.Scale(2)
fmt.Println(rect) // {6 8}Notice you call rect.Scale(2), not (&rect).Scale(2) — Go automatically takes the address for you when you call a pointer-receiver method on an addressable value. The rule of thumb: if a method needs to mutate the receiver, or the struct is large enough that copying it is wasteful, use a pointer receiver. Otherwise a value receiver is simpler. Mixing both styles on the same type is legal but considered bad style — pick one per type and stay consistent.