Anonymous Structs
An anonymous struct is a struct defined without a name. It is useful for data shapes that you only need to use once and don’t intend to reference elsewhere in your codebase.
Syntax
You define the fields and instantiate the struct in a single block.
myCar := struct {
brand string
model string
} {
brand: "Tesla",
model: "Model 3",
}
Use Cases
- JSON Responses: Sometimes you need a specific shape of data for an HTTP response that won’t be used anywhere else.
- Test Cases: Grouping data together for table-driven tests.
When to Avoid
In general, prefer named structs. They improve readability, make your code easier to document, and allow for reusability. Anonymous structs should be reserved for when you are certain the data shape is unique to its current location.