Go by Example: Anonymous Structs
Anonymous structs are one-off data structures defined without a name. They are perfect for temporary data grouping, table-driven tests, and unmarshaling complex JSON without polluting the global namespace.
Code
package main
import (
"encoding/json"
"fmt"
)
func main() {
// 1. Basic Anonymous Struct
// Defined and initialized in one step.
point := struct {
X, Y int
}{
X: 10,
Y: 20,
}
fmt.Printf("Point: %+v\n", point)
// 2. Unmarshaling JSON
// Useful when you only need a subset of fields from a large JSON response.
jsonData := []byte(`{"id": 1, "name": "Gopher", "extra": "ignored"}`)
// We define the struct structure inline.
var user struct {
ID int `json:"id"`
Name string `json:"name"`
}
if err := json.Unmarshal(jsonData, &user); err != nil {
panic(err)
}
fmt.Printf("User: %+v\n", user)
// 3. Table-Driven Tests Pattern
// Anonymous structs are the standard way to define test cases.
tests := []struct {
input int
expected int
}{
{1, 2},
{2, 4},
{3, 6},
}
for _, t := range tests {
fmt.Printf("Input: %d, Expected: %d\n", t.input, t.expected)
}
}
Explanation
In the Go programming language, anonymous structs provide a concise and expressive mechanism for defining temporary, ad-hoc data structures within a localized scope, eliminating the need to pollute the package-level namespace with named types that are only utilized in a single context. These ephemeral structures are declared and instantiated simultaneously, making them exceptionally well-suited for scenarios such as parsing specific subsets of a complex JSON payload where a full data model is unnecessary, or for structuring table-driven tests where input parameters and expected results are grouped together for iteration. By leveraging anonymous structs, developers can write cleaner, more maintainable code that keeps data definitions strictly co-located with the logic that consumes them, thereby enhancing readability and reducing cognitive load.
The utility of anonymous structs extends to their full compatibility with Go's type system features, including field tags for serialization and type inference during initialization. This flexibility allows for powerful patterns, such as decoding a nested configuration object on the fly or aggregating heterogeneous data for a one-time template rendering operation, all while maintaining the strict type safety guarantees that are the hallmark of the language. Consequently, mastering anonymous structs is a key skill for writing idiomatic and efficient Go code, particularly in the domains of web services and testing infrastructure.
- Scoped: Keeps types local to the function.
- JSON: Great for partial unmarshaling.
- Testing: The standard for table-driven tests.
- Type Safety: Fully checked at compile time.

