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);
CodePudding user response:
In Go 1.17 and below, there isn't an easy way to achieve this.
In Go 1.18 (not released yet) you can define a standalone generic map
function like this:
func Map[T, U any](ts []T, mapper func(T) U) []U {
us := make([]U, 0, len(ts))
for _, t := range ts {
us = append(us, mapper(t))
}
return us
}
For the second argument you have to spell out the function literal. There's no conveniency lambda syntax either:
func main() {
res := Map([]int{1, 2, 3, 4, 5}, func(n int) string { return "x" strconv.Itoa(n) })
// res type is []string
fmt.Printf("type: %T, val: %v", res, res) // type: []string, val: [x1 x2 x3 x4 x5]
}
However this is not even close to Javascript prototypes. The prototype chain is an inheritance model. In Go you can't define a method or function that will be inherited by all slice types by virtue of being slices. In Go there isn't a concept of inheritance to begin with.
CodePudding user response:
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