Comment by timmytokyo

Comment by timmytokyo 9 days ago

3 replies

Your example of go code that's harder to read is iterators, and I agree with you. There's no denying that code like this places a high cognitive load on the reader:

  func (al *AssocList[K, V]) All() iter.Seq2[K, V] {
    return func(yield func(K, V) bool) {
      for _, p := range al.lst {
        if !yield(p.key, p.value) {
          return
        }
      }
    }
  }
But the code that actually uses iterators is in my opinion more readable than its non-generic counterpart. So it's really a question of how often you're expected to write (or read) iterators. And I don't expect that most programmers will be writing (or reading) iterators that often.
timmytokyo 9 days ago

On further reflection, I think what makes this example particularly difficult to understand is not so much its use of generics, but the way it uses functions. It's a function that returns a function that takes another function as an argument. The generic [K,V] type arguments are actually pretty straightforward.

chamomeal 9 days ago

I often feel this way about heavy use of typescript generics. The more you lean into the crazy (and awesome) world of generics, the more inscrutable the code becomes to anybody who isn’t a generics wiz. It’s really like an extra language stacked on top of JS. I’ll come back to code I wrote a year ago, and it’ll take me a full day to figure out the types.

But the simplicity of using a library or set of functions that have really nice generics? So awesome. The intellisense and type errors alone can almost be a decent form of documentation.

The source becomes hard and weird to change, but the end result is a very nice DX

Cthulhu_ 9 days ago

I'll admit I've only ever done one serious Go project but I've thankfully never felt a need to use generics, before generics there were the builtin list and map types that were themselves generics.