Description
I'm not sure if this doesn't have some nasty drawback, but I have thought about it several times and would like to share it for your consideration.
Basically its about being able to miss out typing 'struct{}' in literals where its unambiguous.
(i did try making a value and naming it, say 'Nothing := struct{}{} ', but that’s still not great.)
Case 1
a few times, i have composed with types that have no state themselves, say; they implement some default static behaviour to meet an interface.
type Opaque struct{}
func (o Opaque) isOpaque() bool {
return true
}
currently, when made literally, you need to specify the empty struct, which seems a bit redundant/unclear, or use named parameters which often results in stuttering.
type OpaqueColor struct{
Color
Opaque
}
c:=OpaqueColor{Color{},struct{}}
or
c:=OpaqueColor{Color:Color{}}
clearer?
c:=OpaqueColor{Color{}}
imagine if you had several empty types.
case 2.
when you use a map with empty structs values, say to make a set, the literal can get a bit bloated;
(code below cut/paste from a web search.)
cc := &dockerclient.ContainerConfig{
// ...
Volumes: map[string]struct{}{
"foo": struct{}{},
"bar": struct{}{},
},
}
clearer?
cc := &dockerclient.ContainerConfig{
// ...
Volumes: map[string]{"foo","bar"},
}
also, if you change to/from a slice of strings its trivial to update the literal.
case 3
using channels of empty struct{}
done := make(chan struct{})
// ...
done <- struct{}{}
i think this is neater, since empty struct types are all the same anyway
done <- {}