liveBook · Manning

Anonymous struct

As explained in Learn Go with Pocket-Sized Projects

An anonymous struct is a Go struct type declared without a named type identifier.

An anonymous struct is a Go struct type declared inline, without a named type identifier. It is especially useful in table-driven tests, where each case needs only a small set of fields. section 5.1.2 section 5.6

Table-driven test cases

Replace a separately declared testCase type:\n\n type testCase struct {\n input string\n want []rune\n }\n testCases := map[string]testCase\n\nwith an inline anonymous struct:\n\n testCases := map[string]struct {\n input string\n want []rune\n }{\n "5 characters in english": {\n input: "HELLO",\n want: []rune("HELLO"),\n },\n "5 characters in japanese": {\n input: "こんにちは",\n want: []rune("こんにちは"),\n },\n }\n\nThe map key names each test, while the anonymous struct holds the fields required by that case. A named structure remains valid when reuse or a clearer type name is valuable. section 5.1.2 section 5.6

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Defines the inline syntax and contrasts it with a named testCase, but stops short of broader type-system treatment.
Examples
Demonstrates named and anonymous test-case maps covering English, Arabic, Japanese, and invalid-length input.
What it assumes
Assumes familiarity with Go structs, maps, tests, and composite literals while teaching the inline test-case form.
What you can do after
Apply it via Go test tables by declaring map[string]struct{...} and filling only the fields each case needs.
How it connects
Connects anonymous structs with table-driven tests, maps, structs, and test assertions.

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.