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)
Resources
Section titled “Resources”Exercises
Section titled “Exercises”methods1 test
Section titled “methods1 test”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 }methods2 test
Section titled “methods2 test”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