3 ms·
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.
by opensrcken 4y 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.
- eweise 4y agoits worse. You can't do basic things like make a map method.
- liambowen 4y agoWhy can't you? https://github.com/samber/lo/blob/master/slice.go#L20 https://github.com/samber/lo/blob/master/slice.go#L20
- eweise 4y agoyou 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.
- jitl 4y agoTypescript “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.
- mseepgood 4y agohttps://go.dev/doc/faq#generics_comparison https://go.dev/doc/faq#generics_comparison
- DeathArrow 4y agoComing 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.