3

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);
Carol
  • 363
  • 5
  • 16
  • 2
    That can be helpful: https://stackoverflow.com/questions/49468242/idiomatic-replacement-for-map-reduce-filter-etc – Arif Khan Dec 10 '21 at 04:04
  • 1
    The Go standard library does not have this functionality as of Go 1.18. Your choices: seek out third party package, write a for loop, wait for Go 1.19. –  Dec 10 '21 at 04:18
  • Someone made a lodash golang equivalent - https://github.com/samber/lo – mattyb Oct 27 '22 at 00:34

1 Answers1

3

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