liveBook · Manning

User-defined type

As explained in Go in Action, Second Edition

A defined type is a programmer-declared type that creates a distinct named type with an underlying type and can have its own methods.

A user-defined type gives a domain concept its own name and type. In Go, `type Magnitude float32` defines a type whose underlying type is `float32`. The compiler treats `Magnitude` and `float32` as distinct, so mixing their values requires an explicit conversion. That distinction helps prevent an unrelated number from being used as a measurement by accident. section 5.1 section 5.1.1

A defined type is not a type alias. `type A = B` supplies another name for the same type, leaving `A` and `B` interchangeable. A defined type creates a distinct type and can have its own methods. Both forms have uses, but choose a defined type when the distinction carries meaning in the program. section 5.1.1

Model recipe data

Declare `type Unit string` for measurement units and `type Ingredient string` for ingredient names. Although both are backed by strings, their names express different roles. A `Measurement` struct can group a magnitude with a unit; a `Recipe` struct can group a title, yield, and steps. Defined slice and map types can then represent an ingredient list, a recipe box, or a grocery list. section 5.1.1 section 5.2.2

Build larger models by composing smaller types rather than treating every value as a primitive. Embedding a general measurement in specialized types shares its fields and methods; methods and interfaces can then supply behaviors such as converting measurements and scaling recipes. section 5.2.1 section 5.6.2

How Go in Action, Second Edition covers it

How deep it goes
Defines the declaration syntax, contrasts defined types with aliases, and develops struct and collection types into a recipe model.
Examples
Uses measurement magnitudes and units, ingredient lists, recipe steps, and a grocery list.
What it assumes
Assumes familiarity with primitive Go values and introduces defined-type declarations and their role in a larger domain model.
What you can do after
Build it from scratch: define domain-specific Go types and compose them into a recipe model with shared behavior.
How it connects
Connects defined types to structs, slices, maps, embedding, methods, and interfaces.

Also explained in

Compare how 5 books explain user-defined type →

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.