英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论