Hacker News new | ask | show | jobs
by simiones 613 days ago
You can actually (almost) make it work, you just need to add an extra type parameter to keep Go's silly limitations happy [0]:

  strs := []string{"abc", "defgh", "klmnopqrst"}
  ints := From[string, int](strs).
           Map(func(a string) int { return len(a) }).
           Filter(func(a int) bool { return a >= 4 })
  Iterator[int, float32](ints).
           Map(func(a int) float32 { return float32(a) }).
           Each(func(a float32) { fmt.Printf("%v\n", a) })
  //prints 5, then 10
If they allowed the postfix cast syntax to work for non-interface types too, it could have been a single chain, actually (you could do `.(Iterator[int, float32])` inline instead of needing the extra variable.

Note that the original implementation in the article modifies the collections in place, in which case this issue doesn't come up at all: you can't put strings in an array of ints. My implementation creates copies of these collections so that the concept of mapping to a new type actually makes sense.

[0] https://go.dev/play/p/ggWrokAk7nS