Skip to content

Methods

Intermediate · Types & Methods

A method is a function with a receiver. Choose the receiver type deliberately:

  • value receiver (r T) — operates on a copy; use for read-only behavior
  • pointer receiver (r *T) — can mutate the original; use to change state or avoid copying large values

Methods can be defined on any named type you declare in your package, not only structs.

  • methods1 — value (Area) vs pointer (Scale) receivers
  • methods2 — a method on a named non-struct type (Celsius)

Methods attach behavior to a type. A value receiver (r Rectangle) works on a

Show hint
Value receiver reads; pointer receiver mutates:
func (r Rectangle) Area() float64 { return r.Width * r.Height }
func (r *Rectangle) Scale(f float64) { r.Width *= f; r.Height *= f }

Source

You can define methods on ANY named type you declare, not just structs.

Show hint
Convert the named type to its underlying type for arithmetic:
return float64(c)*9/5 + 32

Source