liveBook · Manning

Value receiver

As explained in Go in Action, Second Edition

A value receiver is a method receiver that operates on a copied value of its receiver type rather than on a pointer to that value.

A value receiver lets a method operate on a copied value of its receiver type. It fits conversion methods that calculate and return a new Measurement rather than modifying the receiver. section 5.5

In a measurement conversion model, MetricWeight, ImperialWeight, MetricVolume, and ImperialVolume use value receivers to implement ToImperial and ToMetric. Each method returns a converted Measurement or the original value when no conversion is needed. section 5.5

func (m MetricWeight) ToImperial() Measurement {
	// 1 gram is about 0.035274 ounces
	return Measurement{
		Magnitude: m.Magnitude * 0.035274,
		Unit:      Ounce,
	}
}
func (m MetricWeight) ToMetric() Measurement {
	return m.Measurement
}

func (i ImperialWeight) ToMetric() Measurement {
	// 1 ounce ≈ 28.3495 grams
	return Measurement{
		Magnitude: i.Magnitude * 28.3495,
		Unit:      Gram,
	}
}
func (i ImperialWeight) ToImperial() Measurement {
	return i.Measurement
}

func (m MetricVolume) ToImperial() Measurement {
	// 1 liter ≈ 2.11338 pints
	return Measurement{
		Magnitude: m.Magnitude * 2.11338,
		Unit:      Pint,
	}
}
func (m MetricVolume) ToMetric() Measurement {
	return m.Measurement
}
func (i ImperialVolume) ToMetric() Measurement {
	// 1 pint ≈ 0.473176 liters
	return Measurement{
		Magnitude: i.Magnitude * 0.473176,
		Unit:      Liter,
	}
}
func (i ImperialVolume) ToImperial() Measurement {
	return i.Measurement
}

Compare value-receiver conversion methods that construct new Measurement values with methods that return the receiver's embedded Measurement unchanged. section 5.5

How Go in Action, Second Edition covers it

How deep it goes
Explains the design rationale and shows conversion implementations, but does not develop broader receiver or pointer semantics.
Examples
Demonstrates value receivers through metric and imperial weight and volume conversion methods.
What it assumes
Assumes familiarity with Go methods, structs, interfaces, and specialized measurement types.
What you can do after
Build conversion methods that return new values and satisfy a focused Convertible interface.
How it connects
Connects value receivers to methods, structs, interfaces, polymorphism, and measurement conversion.

Also explained in

Compare how 3 books explain value receiver →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Action, Second Edition. The section links point to the parts of the book it draws on.