How to Use Anonymous Structs in Go

Anonymous structs in Go are inline-defined data structures without a type name, used for temporary or one-off field groupings.

Anonymous structs in Go are defined inline using the struct{} syntax without a preceding type name, allowing you to create temporary or one-off data structures. You declare them by listing fields directly inside the curly braces, optionally with tags, and initialize them using the same literal syntax.

// Define and initialize an anonymous struct inline
user := struct {
    Name  string
    Email string
}{
    Name:  "Alice",
    Email: "alice@example.com",
}

// Access fields directly
fmt.Println(user.Name)

// Use in function arguments or return values
func greet(u struct{ Name string }) {
    fmt.Println("Hello", u.Name)
}
greet(user)