Anonymous Structs

An anonymous struct is just like a normal struct, but it is defined without a name and therefore cannot be referenced elsewhere in the code.

To create an anonymous struct, instantiate the instance immediately using a second pair of braces after declaring the type:

example.go
myCar := struct {
  brand string
  model string
}{
  brand: "Toyota",
  model: "Camry",
}

You can also nest anonymous structs as fields within other structs:

nested.go
type car struct {
  brand   string
  model   string
  doors   int
  mileage int
  // wheel is a field containing an anonymous struct
  wheel struct {
    radius   int
    material string
  }
}

var myCar = car{
  brand:   "Rezvani",
  model:   "Vengeance",
  doors:   4,
  mileage: 35000,
  wheel: struct {
    radius   int
    material string
  }{
    radius:   35,
    material: "alloy",
  },
}
circle-info

When Should You Use an Anonymous Struct?

Prefer named structs in general β€” they improve readability and are reusable. Anonymous structs are useful when you know the struct will only be used once (for example, to shape JSON data in an HTTP handler). If a struct is only meant to be used once, declaring it anonymously can discourage accidental reuse.

You can read more about anonymous structs here: https://blog.boot.dev/golang/anonymous-structs-golang/