Update 2022-12-30T15:54:00Z Turns out nameless fields are absolutely useless for most things because they are private and not exported.
I’ve known for a long time about anonymous structs but had no idea there is a thing called anonymous fields.1 If a field doesn’t have a name, then the type is used as the name. It appears that only primitives work this way. An anonymous slice doesn’t seem to work.
package main
import "fmt"
type Foo struct { any }
type Bar struct { any }
func main() {
same := &struct{ string }{`some`}
foo := Foo{same}
bar := Bar{same}
fmt.Printf("%v (%[1]T) %v (%[2]T)\n", foo, bar)
fmt.Printf("%v (%[1]T) %v (%[2]T)\n", foo.any, bar.any)
}
{0xc000010250} (main.Foo) {0xc000010250} (main.Bar)
&{some} (*struct { string }) &{some} (*struct { string })
And you cannot use slices:
# command-line-arguments
/tmp/foo.go:10:2: syntax error: unexpected [, expecting field name or embedded type
The number of search hits that contain the word “anonymous” and “fields” that come back with boring explanations of anonymous structs (which are not the same as anonymous fields in a struct) is absolutely ridiculous. Almost nothing out there covers anonymous struct fields, so I don’t feel so bad having read about them and completely obliterating them from my memory (and neither should you). ↩