liveBook · Manning

Struct

As explained in Go in Action, Second Edition

The struct keyword introduces a Go struct type declaration.

When related values need to travel together, define a struct. The `struct` keyword introduces a set of named, typed fields; each field is accessed with dot notation. A struct can stand alone as a one-off value, but giving it a type name makes the definition reusable. section 3.6 section 3.6.1

Listing 3.22 Using a type in a declaration
type person struct {
	name string
	age  int
}

andy := person{
	name: "Andy",
	age:  42,
}
james := person{
	name: "James",
	age:  26,
}
fmt.Println(andy.name, andy.age)   // output: Andy 42
fmt.Println(james.name, james.age) // output: James 26

A named `person` type gives two values the same field definitions. Its keyed literals supply field values, and dot notation reads them. section 3.6.1

A recipe measurement illustrates the design payoff: a `Measurement` struct groups a `Magnitude` and a `Unit` into one domain value. Fields can use built-in types, named types, or other structs. A keyed literal such as `Measurement{Magnitude: 200, Unit: Gram}` creates a value; omitting `Magnitude` leaves it at its zero value. Multiline literals require a trailing comma after the final field value. section 5.1.2 section 3.6

As the domain model grows:

  • Use capitalized field names when other packages need access; lowercase names remain unexported. section 5.1.2
  • Combine structs with named types, embedding, methods, interfaces, and collections to model recipe steps, ingredients, scaling, and grocery lists. section 5.6.2 section 5.7

How Go in Action, Second Edition covers it

How deep it goes
Works through declarations, fields, literals, access, and visibility, then connects structs to larger models without detailing their runtime representation.
Examples
Uses a reusable person declaration and recipe measurements, then assembles ingredients and steps into a scalable recipe.
What it assumes
Assumes familiarity with basic Go values and declarations while teaching struct declaration and field access directly.
What you can do after
Build it from scratch: define and initialize a named struct, access its fields, and use it to represent related domain data.
How it connects
Connects structs to named types, composition, methods, interfaces, and collections.

Also explained in

Compare how 14 books explain struct →

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.