Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic Replacement for map/reduce/filter/etc

Tags:

go

I have a list of things in a go program. I want to loop over them, and perform some operation on/with a subset of those things. Is there more elegant/idiomatic code for doing this than the following?

for key, value := range listOfThings {
    if(!value.Enabled) {
        continue;
    }

    doTheThing(key, value)
}

The large context -- I'm coming from languages where map/reduce/filter/etc are popular patterns for this sort of thing, but word on the internet is that those sorts of higher level abstractions aren't really a go-ish thing to do.

Is there something more elegant than guard/continue clauses in my range blocks for this sort of code?

like image 355
Alan Storm Avatar asked Mar 24 '18 18:03

Alan Storm


2 Answers

Simple apply/filter/reduce package.

I wanted to see how hard it was to implement this sort of thing in Go, with as nice an API as I could manage. It wasn't hard.

Having written it a couple of years ago, I haven't had occasion to use it once. Instead, I just use "for" loops.

You shouldn't use it either.

Rob Pike


Follow Rob's advice. Use for loops.

like image 62
peterSO Avatar answered Oct 16 '22 06:10

peterSO


If you're still interested, the go-funk package will enable you to do map/reduce/filter etc.

This library is at the time of answering regularly updated. The previous library mentioned hasn't been updated in 4 years.

Github - Go Funk

like image 33
Clement Avatar answered Oct 16 '22 06:10

Clement