6

I thought I'd be able to make an ordered map type by using anonymous fields:

type customMap struct{
    map[string]string
    ordered []string
}

where I could reference the map with customMapInstance["key"] and iterate over ordered. Alas, it appears arrays and maps are not valid anonymous fields. I suspect there's a good reason...

Ethan
  • 1,057
  • 1
  • 14
  • 23
  • You can see here (http://stackoverflow.com/a/26194639/6309) another attempt at embedding an unnamed type. It failed too. – VonC Oct 19 '14 at 04:20

1 Answers1

8

From the spec:

An embedded type must be specified as a type name T or as a pointer to a non-interface type name *T, and T itself may not be a pointer type.

You see that it mentions a "type name".

Named types are specified by a (possibly qualified) type name; unnamed types are specified using a type literal, which composes a new type from existing types.

In other words, a map or slice may not be anonymous unless they are defined as a named type. For example:

type MyMap map[string]string

type customMap struct{
    MyMap
    ordered []string
}

However, even if you embed MyMap or a slice type, you would still not be able to index customMap. Only fields and methods may be "promoted" when you embed. For everything else they act as just another field. In the above example, MyMap doesn't have any fields or methods and therefore is equivalent to:

type customMap struct{
    MyMap MyMap
    ordered []string
}
Stephen Weinberg
  • 51,320
  • 14
  • 134
  • 113
  • I had actually tried naming before embedding, but alas. I haven't looked at the implementation, but indexing a map sounds like calling a `m.hashTableLookup(key interface{})` function, in which case it could potentially be promoted, yes? Same thing for channels and sending/receiving. It would be really great if you could use the lovely `[ ]` and `<-` syntax directly on structs. – Ethan Oct 19 '14 at 05:37
  • This is not like python or other dynamic languages where indexing syntax is a call to a magic method. Using [] or <- directly on a struct is impossible. – Stephen Weinberg Oct 19 '14 at 07:49
  • Then why can you embed `string` anonymously? [go playground link](https://play.golang.org/p/qS4t-FLoP2M) – Ibraheem Ahmed Sep 16 '20 at 20:29
  • The Go spec has had many changes to it over the years. "Named type" and even "anonymous field" are no longer terms used by the spec. However, string was considered a named type at the time I wrote the original answer. Unnamed types were composed types such as a struct, slice, map, etc that are represented as a type literal and don't have an identifier as a name. – Stephen Weinberg Sep 18 '20 at 00:31