Shorter Way to Transform List Elements in Go
In Python, applying a function to each element in a list can be achieved using list comprehensions. However, in Go, a more verbose approach involving a loop is commonly used. This question explores a concise way to accomplish this operation in Go.
Python Solution:
list = [1,2,3] str = ', '.join(multiply(x, 2) for x in list)
Go Solution (Original):
list := []int{1,2,3} list2 := []int for _,x := range list { list2 := append(list2, multiply(x, 2)) } str := strings.Join(list2, ", ")
Shorter Go Solution (Go 1.18 ):
func Map[T, V any](ts []T, fn func(T) V) []V { result := make([]V, len(ts)) for i, t := range ts { result[i] = fn(t) } return result }
Usage:
input := []int{4, 5, 3} outputInts := Map(input, func(item int) int { return item + 1 }) outputStrings := Map(input, func(item int) string { return fmt.Sprintf("Item:%d", item) })
This Map function offers a concise and generic way to apply a function to a list of any type, resulting in a new list of transformed values.
The above is the detailed content of How to Transform List Elements Concisely in Go?. For more information, please follow other related articles on the PHP Chinese website!