Home > Backend Development > Golang > How to Transform List Elements Concisely in Go?

How to Transform List Elements Concisely in Go?

Mary-Kate Olsen
Release: 2024-11-10 18:03:02
Original
343 people have browsed it

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

Go Solution (Original):

list := []int{1,2,3}
list2 := []int

for _,x := range list {
    list2 := append(list2, multiply(x, 2))
}

str := strings.Join(list2, ", ")
Copy after login

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

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

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!

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