Anonymous ("transparent") structures are a good thing in programming languages

I recently wrote about learning how C unions can be used to create optional namespaces , by creative use of both anonymous unions and anonymous structs. However, the problem in that entry is not that modern C has anonymous unions and structs (officially added in C11, a GNU extension before then, and before that a Plan 9 one). I think that what we could call "transparent" structures are a good thing in any language, not just C (Go has them too, and probably other languages as well).

Let's start with a traditional C sub-struct:

struct common {
  int field1;
  void *field2;
};
struct fred {
  struct common sub;
  [...]
};

The sub struct is two things in one; it's both a namespace ( fred.sub ) and a collection of reusable field definitions. However, there's no particular reason why these thing should always have to go together, so that you're forced to create a new namespace (and exile things into it) any time you want a collection of common fields. Back when traditional C gave you no choice, people built various hacks to get common fields without the namespaces (for example, a #define that defined all of your common fields together). In Go, where this has been legal since the beginning, I believe that this "embedding" is reasonably popular, showing that there is real demand (and use) for it.

(In C11, anonymous structs and unions must be completely anonymous, without a name for the new struct or union type, but in other C dialects and other languages you can be more flexible. See the GCC documentation on Unnamed Structure and Union Fields . I'm using the term "transparent" to cover all cases where the sub-structure has no overall name and the names of its fields are directly usable, as if they were top-level fields.)

It doesn't make much sense to have namespaces without something in them, but as we've seen there's a desire to not always have to use the name of the namespace to refer to things inside it. I don't know if anyone has come up with a good syntax for this (in any language).

PS: Go officially supports fairly liberal struct embedding , but in practice its full generality is rarely used.