anonymous struct and empty struct

Note that one interesting aspect of using struct{} for the type pushed to a channel (as opposed to int or bool), is that the size of an empty struct is… 0!

See the recent article “The empty struct” (March 2014) by Dave Cheney.

You can create as many struct{} as you want (struct{}{}) to push them to your channel: your memory won’t be affected.
But you can use it for signaling between go routines, as illustrated in “Curious Channels“.

finish := make(chan struct{})

As the behaviour of the close(finish) relies on signalling the close of the channel, not the value sent or received, declaring finish to be of type chan struct{} says that the channel contains no value; we’re only interested in its closed property.

And you retain all the other advantages linked to a struct:

  • you can define methods on it (that type can be a method receiver)
  • you can implement an interface (with said methods you just define on your empty struct)
  • as a singleton

in Go you can use an empty struct, and store all your data in global variables. There will only be one instance of the type, since all empty structs are interchangeable.

See for instance the global var errServerKeyExchange in the file where the empty struct rsaKeyAgreement is defined.

Leave a Comment