Home > Back-end >  Is there a way to map an array of objects in golang?
Is there a way to map an array of objects in golang?

Time:03-26

Coming from Nodejs, I could do something like:

// given an array `list` of objects with a field `fruit`:

fruits = list.map(el => el.fruit) # which will return an array of fruit strings 

Any way to do that in an elegant one liner in golang?

I know I can do it with a range loop, but I am looking for the possibility of a one liner solution

CodePudding user response:

In Go, arrays are inflexible (because their length is encoded in their type) and costly to pass to functions (because a function operates on a copy of its array arguments). I'm assuming you'd like to operate on slices rather than on arrays.

Because methods cannot take additional type arguments, you cannot simply declare a generic Map method in Go. However, you can define Map as a generic function:

func Map[T, U any](ts []T, f func(T) U) []U {
    us := make([]U, len(ts))
    for i := range ts {
        us[i] = f(ts[i])
    }
    return us
}

Then you can write the following code,

names := []string{"Alice", "Bob", "Carol"}
fmt.Println(Map(names, utf8.RuneCountInString))

which prints [5 3 5] to stdout (try it out in this Playground).

Go 1.18 saw the addition of a golang.org/x/exp/slices package, which provides many convenient operations on slices, but a map function is noticeably absent from it. If I remember correctly, that omission was the result of a conscious decision: in Go, you don't want to hide the cost of operations (here, the allocation of a new slice) behind one-liners. Russ Cox ultimately elected to drop Map from the proposal because it's

probably better as part of a more comprehensive streams API somewhere else.

CodePudding user response:

You can use this package https://pkg.go.dev/github.com/samber/lo#Map

or you can see the code in that repo.

this is the playground

  • Related