Home > Backend Development > Golang > How Can I Efficiently Map an Array of Objects in Go?

How Can I Efficiently Map an Array of Objects in Go?

Linda Hamilton
Release: 2024-12-19 11:44:10
Original
465 people have browsed it

How Can I Efficiently Map an Array of Objects in Go?

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
}
Copy after login

Now, you can use this function as follows:

names := []string{"Alice", "Bob", "Carol"}
fmt.Println(Map(names, utf8.RuneCountInString)) // Output: [5 3 5]
Copy after login

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:

  • Hidden costs of operations within one-liners
  • Uncertain error handling within Map
  • Encouraging a style that deviates from Go's traditional approach

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template