4 ms·
Go needs functions that support parametric types for collections. I'm not even talking about generics here as user defined types. Let's forget about generics or
by spriggan3 10y ago
Go needs functions that support parametric types for collections. I'm not even talking about generics here as user defined types. Let's forget about generics or "the ability for developers to implement their own type safe containers".
Let's talk about the fact that functions in Go could support type parameters in signatures , something like :
func Map<V,W>(slice []V,func(element V)W)[]W {
// ...
}
What we have here is a guarantee that at compile time, this code is safe. We didn't introduce generics, slice is a Go slice of V and the result is a go slice of W.
The code should then be used this way :
result := Map<string,string>([]string{"a","b"},
func(e string)string{ return e+"foo" } )
This is completely type safe, no reflection is used, the compiler knows all the types at compile time and no generic type was introduced. This is a good trade off and merely syntactic sugar that would enable developers to get rid of interface {} parameter + type assertions.
- catnaroek 10y agoThis is nice, but generic functions are still generics.
- spriggan3 10y agoGo already has generic functions : append, copy ... that are type safe at compile time, how do you think they are implemented in the source code of Go's compiler? Just like I said. Go compiler finds "append" token, and go look up if both arguments and the return type match, not at run time, at compile time.
- catnaroek 10y agoNo disagreement. I was just pointing out that what you were asking for is in fact user-defined generics.
- scott_s 10y agoIn fact, if I understand spriggan3's proposal correctly, that's how Java's generics work. The approach is usually called type-erasure. (https://docs.oracle.com/javase/tutorial/java/generics/erasure.html https://docs.oracle.com/javase/tutorial/java/generics/erasur...)