douzhan1963 2018-03-24 18:19
浏览 47
已采纳

映射/缩小/过滤器/等的惯用替换

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?

  • 写回答

2条回答 默认 最新

  • dougu1985 2018-03-24 20:05
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 如何将下列的“无限压缩存储器”设计出来
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口