"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Go language list elements concise conversion techniques

Go language list elements concise conversion techniques

Posted on 2025-04-17
Browse:202

How to Transform List Elements Concisely in Go?

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3