3 ms·
One thing I think generics in Go is missing is the <?> concept in Java. If you're taking a List[T] and all you want to do is to call list.size() then you don't
by adrianmsmith 2mo ago
One thing I think generics in Go is missing is the <?> concept in Java.
If you're taking a List[T] and all you want to do is to call list.size() then you don't care what type of list it is. In Java you can write a function which takes a List<?> but in Go you have to write List[T] so then the question becomes what is T?
You have to make the function (or type you're a method on) generic. If you make the type generic then every user of your type also needs to specify T, etc.
I don't think it would be impossible to add that to Go. Allow List[?], which matches a List with any type parameter. Calling functions which don't involve the type parameter like list.size() would be fine, calling a method returning the type parameter like list.get(n) would return "any", and methods taking the type parameter like list.set(n, obj) would probably not be callable.
- Hendrikto 2mo agoGo Generics work differently than those in Java. They are specialized, meaning that they are not generic at runtime anymore. Instead, the compiler creates a different implementation for each type. At runtime, there are only List[int], List[string], etc. List[T] is not a thing anymore.
- lowmagnet 2mo agoThe one thing I hated about Java's generics was type erasure. It worked for the JVM but it had such stupid limits, like not being able to switch on a type, like go. (interfaces are types, this is exploitable)
- kbolino 2mo agoYou need this in Java because interfaces are explicitly implemented. You don't need this in Go because interfaces are structurally implemented. The way you spell "anything that has a method named Size which returns int" is interface{Size() int}.