liveBook · Manning

Immutable collection

As explained in Learn Go with Pocket-Sized Projects

Immutability is the property of a value or object whose state cannot be changed after construction.

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

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains hidden fields, construction, derived methods, and thread safety, but does not detail collection-specific mutation mechanisms.
Examples
Demonstrates immutable Currency, Amount, Decimal, and FormattedWeek values with hidden fields and read-only methods.
What it assumes
Assumes familiarity with Go structs and methods while teaching custom value types and hidden representation through examples.
What you can do after
Build it from scratch in Go by hiding fields, constructing complete values, and exposing non-mutating methods.
How it connects
Connects immutability with value objects, constructors, methods, structs, and thread safety.

Also explained in

Compare how 24 books explain immutable collection →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.