Does Go support functional programming?

Viewed 572

As in java8:

someList.stream().map(e->e.getXXX()).toList()

For example, I have a Student array/slice, and the struct Student contains properties like Id, Name, and so on.

I want to extract all Ids into a NEW array/slice with one-line code like java8 as mentioned above, instead of range. Is there is an example?

1 Answers

Currently there is not an easy, builtin way to do this. Although Go has first-class functions and lexical closure, it's not possible to write a function like map that will operate on arbitrary types in the way you want. (Also, there's no compact lambda syntax, but I consider that a relatively minor issue).

Instead, you have to do one of the following:

  1. Operate on interface{}. While this would let you write a func map([]interface{}, func(interface{})interface{}) []interface{}, you lose compile-time type safety, you lose performance, and a []interface{} is not a []string (or whatever the type is of the field you wanted to fetch), nor can you even type-assert it to one, so working with the result is cumbersome.
  2. Use code-generation. There are libraries out there that will generate map/filter/etc. code for you, specialized to given types, so that none of the disadvantages of #1 apply. And Go ships with a Go parser in the standard library, so most code generators are fairly robust. But code generation is a separate build step, hampers debuggability, and can hurt the clarity of code.
  3. Just live with boilerplate, writing lots of loops, and forget about trying to achieve functional style.
  4. Wait for Go 1.18 to bring generics, which should make libraries of functional idioms a lot more practical.

Most experienced Go users would recommend approach #3, and so do I (reluctantly).

Related