Hacker News new | ask | show | jobs
by opensrcken 1512 days ago
As someone who tried out Go before generics and didn't like it, I'm curious how Go generics compare to generics in Java or Typescript.
4 comments

Typescript “generics” (type parameters) are probably the most powerful such feature in a mainstream language at the type level. Of course neither Java or Typescript generics improve code performance versus the T<any> or T<Object> version; whereas the Go version will improve performance due to memory stenciling or whatever they call it - memory allocation shape is improved and data is actually inlined into the container struct, so you can avoid pointer chasing all together if that’s your goal.

But there are two major drawbacks in Go generics now:

1. Methods cannot be generic, so you can’t do any chaining-style interfaces like thing.Map(…).Reduce(…) if you want to output a different type.

2. Possibly even worse: you cannot cast from Container[ConcreteType] to Container[any], or from Container[any] to Container[ConcreteType]. In my limited experimentation this was the most surprising blocker for me since it’s quite natural to work with Container<unknown> in Typescript, and possible (although I’m not sure how idiomatic) to do Container<Object> or Container<*> in Java/Kotlin.

Still when writing “normal” Go (as opposed to trying to abuse the type system), the generic slices package is a noticeable pain relief. But I actually don’t find myself implementing generic containers too much in the Go domain.

Coming from a C++, C#, Java background, the implementation of generics in Go seems half baked and less useful. Of course, it is better this way than no generics at all.
its worse. You can't do basic things like make a map method.
you can do it that way but you can't add the map method to a struct like persons.map() which would allow you to chain methods. But I guess with the multiple return value convention, you can't chain anyway very nicely.