I am playing with Go but I am having a very hard time doing things that are very simple in other languages.
I\'d like to reproduce a similar syntax:
Interestingly enough, Rob Pike just proposed (18 hours ago) the library filter which does a bit what you want:
See for instance Choose()
// Choose takes a slice of type []T and a function of type func(T) bool. (If
// the input conditions are not satisfied, Choose panics.) It returns a newly
// allocated slice containing only those elements of the input slice that
// satisfy the function.
Tested here:
func TestChoose(t *testing.T) {
a := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
expect := []int{2, 4, 6, 8}
result := Choose(a, isEven)
As twotwotwo points out in the comments, the GoDoc for this library states:
Package
filtercontains utility functions for filtering slices through the distributed application of a filter function.The package is an experiment to see how easy it is to write such things in Go. It is easy, but
forloops are just as easy and more efficient.You should not use this package.
This caveat is reflected in the document "Summary of Go Generics Discussions", section "Functional Code":
These are the usual higher-order functions such as
map,reduce(fold),filter,zipetc.Cases:
typesafe data transformations:map,fold,zipPros for using generics:
Concise way to express data transformations.Cons for using generics:
The fastest solution needs to take into account when and which order to apply those transformations, and how much data is generated at each step.
It is harder to read for beginners.Alternative solutions:
use
forloops and usual language constructs.