In Node.js, the map() function allows you to create a new array by transforming each element of the original array. In Go, arrays are not as flexible as slices and do not support methods.
However, you can implement a generic Map function that can be used to transform an array of objects into an array of their desired values.
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 }
fruits := []struct{ fruit string }{ {fruit: "apple"}, {fruit: "banana"}, {fruit: "cherry"}, } fruitNames := Map(fruits, func(fruit struct{ fruit string }) string { return fruit.fruit }) fmt.Println(fruitNames) // Outputs: [apple banana cherry]
While using a one-liner Map function can be convenient, it's important to consider its limitations:
Despite these considerations, the Map function can provide a lightweight and elegant solution for mapping arrays of objects in Go.
The above is the detailed content of How Can I Map Arrays of Objects in Go?. For more information, please follow other related articles on the PHP Chinese website!