Go

What are anonymous structs and struct tags? When would you use an anonymous struct in tests or JSON handling?

Question 561MediumGo 1.22 to 1.25

An anonymous struct is a struct type written inline without a name. Struct tags are raw string metadata on fields, read through reflection (reflect.StructTag.Get) by encoders, ORMs and validators. The convention is space-separated key:"value" pairs, and go vet flags malformed tags.

func TestParse(t *testing.T) {
	tests := []struct {
		name    string
		in      string
		want    int
		wantErr bool
	}{
		{name: "ok", in: "42", want: 42},
		{name: "bad", in: "x", wantErr: true},
	}
	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			got, err := strconv.Atoi(tc.in)
			if (err != nil) != tc.wantErr || got != tc.want {
				t.Fatalf("Atoi(%q) = %d, %v", tc.in, got, err)
			}
		})
	}
}

func writeJSON(w http.ResponseWriter, u User) error {
	// one-off response shape without declaring a package-level type
	return json.NewEncoder(w).Encode(struct {
		ID    int64     `json:"id"`
		Email string    `json:"email,omitempty"`
		Since time.Time `json:"since,omitzero"` // Go 1.24: omits the zero time
		Pass  string    `json:"-"`              // never serialized
	}{ID: u.ID, Email: u.Email, Since: u.Created})
}

Uses: table-driven tests, ad-hoc request/response DTOs, decoding just the fields you need from a large JSON payload, and grouping related globals (var config struct{ ... }). Gotchas: unexported fields are ignored by encoding/json even if they have tags. omitempty does not omit zero structs such as time.Time; use omitzero (1.24+), which also respects an IsZero() method. Two anonymous struct types with identical fields and tags are identical types and can be assigned to each other. Tags must match exactly, although conversion between the types ignores tags.

More on Go Idioms, Design Patterns & Language Design

All 16 Go Idioms, Design Patterns & Language Design questions