-2

I came across this in lecture notes:

setCollection := map[string]struct{}{
        "uniqElement1": {},
        "uniqElement2": {},
        "uniqElement3": {},
}

As I understand, {} here represents the empty struct, but I never saw this before. Does this always mean an empty struct? Also, when can we use this notation? This code doesn't work:

setCollection["newElem"] = {}
Riko Ou
  • 5
  • 2

1 Answers1

1

{ and } are syntax requirement of composite literal values.

Your first example uses a composite literal to create a map value, and inside that literal it uses other struct literals for the key values of the map. And the Spec allows to omit the inner type in the inner literal:

Within a composite literal of array, slice, or map type T, elements or map keys that are themselves composite literals may elide the respective literal type if it is identical to the element or key type of T. Similarly, elements or keys that are addresses of composite literals may elide the &T when the element or key type is *T.

Your second example tries to use {} not in a composite literal, and the compiler does not know what type you want to use. So it's a compile time error. You have to be explicit in the second example:

setCollection["newElem"] = struct{}{}

Where struct{} is the type, and struct{}{} is a composite literal value (of type struct{}).

See related: How do struct{} and struct{}{} work in Go?

icza
  • 389,944
  • 63
  • 907
  • 827