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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With