A method is a function associated with a type through a receiver, grouping behavior with the data it operates on. Go permits value and pointer receivers, making receiver choice part of the implementation design. section 5.4
Choose the receiver according to the method’s effect and the receiver’s size:
- Use a value receiver when the method reads the receiver without changing it, such as converting ImperialWeight to a metric Measurement; the method works on a copy. section 5.4
- Use a pointer receiver when the method updates receiver state or when copying a large struct is undesirable; changes remain visible on the original value. section 5.4
- Attach methods to domain types to keep operations such as scaling recipes and converting measurements near the data they govern. section 5.4 section 5.6.2
Scaling a recipe
A Recipe can expose AddStep and Scale methods. AddStep appends a preparation step, while Scale uses a pointer receiver to multiply ingredient measurements and the recipe yield in place. Calling recipe.Scale(2) then prints the updated recipe. section 5.6.2
func (i ImperialWeight) ToMetric() Measurement {
// 1 ounce ≈ 28.3495 grams
return Measurement{
Magnitude: i.Magnitude * 28.3495,
Unit: Gram,
}
}
Inspect a value-receiver method that converts ImperialWeight without modifying the original value. section 5.4
// Scale multiplies the ingredient amounts by a factor.
func (r *Recipe) Scale(factor uint) {
for i := range r.Steps {
for j := range r.Steps[i].Ingredients { #1
r.Steps[i].Ingredients[j].Measurement = scaleMeasurement(r.Steps[i].Ingredients[j].Measurement, float32(factor)) #2
}
}
r.Yield *= factor
}
func (r *Recipe) AddStep(step Step) {
r.Steps = append(r.Steps, step)
}
func scaleMeasurement(m Convertible, factor float32) Convertible {
switch v := m.(type) {
case MetricWeight:
return MetricWeight{Measurement{v.Magnitude * Magnitude(factor), v.Unit}}
case ImperialWeight:
return ImperialWeight{Measurement{v.Magnitude * Magnitude(factor), v.Unit}}
default:
return m
}
}
Inspect pointer-receiver methods that mutate Recipe and a helper that scales concrete measurement types. section 5.4



















