Home >Backend Development >Golang >How Can I Efficiently Map Arrays of Objects in Go Using a Generic Function?
Mapping Arrays of Objects Using a Generic Function
In Go, functions operating on arrays have certain limitations due to their inflexible nature and overhead associated with copying arguments. This article explores an approach to map arrays of objects in a concise manner using a generic top-level function.
To map an array of objects in Go with a one-liner, you can define a generic function named Map as follows:
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 }
This function takes an array of type T and a function f that takes a parameter of type T and returns a value of type U. It returns an array of type U containing the mapped values.
To map an array of objects, you can use the Map function like this:
names := []string{"Alice", "Bob", "Carol"} fmt.Println(Map(names, utf8.RuneCountInString))
This code will print the following output to stdout:
[5 3 5]
The Map function is based on a loop and can introduce overhead compared to native functions operating on arrays. It's important to weigh the benefits of concise syntax against the potential performance implications.
The above is the detailed content of How Can I Efficiently Map Arrays of Objects in Go Using a Generic Function?. For more information, please follow other related articles on the PHP Chinese website!