Mapping an Array of Objects in Go
In Node.js, you can use the map function to transform an array of objects into an array of values. Wondering how to achieve this in Go with conciseness?
Go Solution: Map as a Top-Level Function
Unlike methods in Go, top-level functions can take additional type arguments. Using this, we 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 }
Now, you can use this function as follows:
names := []string{"Alice", "Bob", "Carol"} fmt.Println(Map(names, utf8.RuneCountInString)) // Output: [5 3 5]
Historical Context: Why Map is Absent in Standard Go Libraries
Prior to Go 1.18, extensive discussions in the GitHub issue for the golang.org/x/exp/slices proposal considered adding a Map function but ultimately decided against it due to concerns about:
Streams API is considered a potential future home for such a function.
The above is the detailed content of How Can I Efficiently Map an Array of Objects in Go?. For more information, please follow other related articles on the PHP Chinese website!