3 ms·
Yes, it's not restricted to generics. But the reason the alias was introduced is generics. Because they use interfaces to specify bounds (constraints) for type
by mseepgood 5y ago
Yes, it's not restricted to generics. But the reason the alias was introduced is generics. Because they use interfaces to specify bounds (constraints) for type parameters (bounded polymorphism): [T fmt.Stringer], [T io.Reader], ...
So an unbounded type parameter is [T interface{}], or [T any] when using the shorter alias. It's a type alias / predeclared identifier defined in the universe scope:
type any = interface{}
- eweise 5y agoCouldn't unbounded just be [T]? Why the extra typing?
- Intermernet 5y agoIt's not really extra typing. It's just a syntactic convenience considered beneficial by the core team. It doesn't actually break compiler parsing in any way, but it may lead to human confusion in cases where a variable or constant has been named "any". This is probably very rare, and the code will still compile.
- mseepgood 5y agoNo, that would be a parsing ambiguity with arrays. And the consistency of type parameter lists with normal parameter lists where types are mandatory is an additional benefit.
- handrous 5y agoMakes it much less likely someone will accidentally define a type as "any".
- MadcapJake 5y agoI am not well-versed in Go, but isn't it because Go supports specifying multiple parameters with the same type by just using a comma. Your suggestion would lead to syntactic ambiguity except when only a single parameter is provided. Additionally one can provide only types when parameter values are not needed and this requires there to be a typename to differentiate between no parameters.
- earthboundkid 5y agoWith generics, the metatype of a type variable is an interface type. If you just had T, it’s grammatically incomplete because you don’t specify the metatype. I guess you could just assume the any type if it’s incomplete, but that’s an unnecessary inconsistency in the grammar.
- eweise 5y agoI don't know. Making constraints optional is the way it works in all the other languages I use.