What are anonymous structs and struct tags? When would you use an anonymous struct in tests or JSON handling?
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
- Q559How do you implement a circuit breaker and bulkhead in Go? What state machine and concurrency concerns are involved?
- Q560What are the uses of the blank identifier (_)? Explain import _, var _ = , _ = x and blank struct fields.
- Q562How do you design an idempotent HTTP API handler in Go (idempotency keys, storage, concurrency)?
- Q563Compare Go with Java, Rust, and Python for backend services: concurrency model, memory management, error handling and deployment. When would you not choose Go?