Immutability means that a value or object cannot change after construction. In Go, hide state inside a custom struct, construct complete values, and expose methods that read or derive results without changing the instance. section 6.1.1 section 11.5.1
Use immutability to make value-like objects predictable:
- Keep fields unexported so external callers cannot replace the stored state directly. section 6.1.1
- Return a fully constructed value from a constructor such as NewFormattedWeek. section 11.5.1
- Expose methods such as Start and End for access or formatting rather than mutation. section 11.5.1
- Prefer the design when representing value objects such as money or a calculated week; immutable objects are inherently thread safe. section 6.1.1 section 11.5.1
Money and formatted weeks
A Currency hides its code, while Amount groups a quantity with a currency. A FormattedWeek stores calculated start and end times during construction and later formats them through Start and End, preventing later calls from changing the represented period. section 6.1.1 section 11.5.1
Listing 11.35 week.go: API
// FormattedWeek defines the start and end of a week, and formats them.
// Start to end will be from Sunday 00:00 to Saturday 23:59,
// rounded to the minute.
type FormattedWeek struct {} #1
// NewFormattedWeek builds an immutable week from one moment inside it.
func NewFormattedWeek(include time.Time) FormattedWeek #2
// Start returns the formatted first day of the week.
func (w FormattedWeek) Start() string #3
// End returns the formatted last day of the week.
func (w FormattedWeek) End() string#3
Shows an immutable Go value object with a constructor and read-only formatting methods. section 11.5.1























