在Golang中,Array.prototype.map()的等效函数是什么?

huangapple go评论81阅读模式
英文:

What is the equivalent function of Array.prototype.map() in Golang?

问题

我想在Go语言中做类似这样的内联函数,并且不想编写for循环...

const userIds = Users.map(func(u User) int {
    return u.Id
})
英文:

I would like do something like this inline function in go, and don't want to write a for loop...

const userIds = Users.map(u => u.Id);

答案1

得分: 3

我建议使用一个名为go-funk的包来操作数组/切片。
它在某些方面类似于lodash。
你的代码可能如下所示:

userIds := funk.Map(Users, func(u structTypeOfUser) int {
        return u.Id
}).([]int);

它支持许多其他熟悉的函数,如find、reduce、filter、contains(include)...
该包的存储库地址:
https://github.com/thoas/go-funk

英文:

I suggest using a package named go-funk to manupulate array/slice.
It may look like lodash in some aspects
Your code may look like this:

userIds := funk.Map(Users, func(u structTypeOfUser) int {
        return u.Id
}).([]int);

It supports many other familiar functions like find, reduce, filter, contains(include)...
Repository of that package:
https://github.com/thoas/go-funk

huangapple
  • 本文由 发表于 2021年12月10日 12:01:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/70299620.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定