Short way to apply a function to all elements in a list in golang

Issue

Suppose I would like to apply a function to every element in a list, and then put the resulting values in another list so I can immediately use them. In python, I would do something like this:

list = [1,2,3]
str = ', '.join(multiply(x, 2) for x in list)

In Go, I do something like this:

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

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

str := strings.Join(list2, ", ")

Is it possible to do this in a shorter way?

Solution

I would do exactly as you did, with a few tweaks to fix typos

import (
    "fmt"
    "strconv"
    "strings"
)

func main() {
    list := []int{1,2,3}

    var list2 []string
    for _, x := range list {
        list2 = append(list2, strconv.Itoa(x * 2))  // note the = instead of :=
    }

    str := strings.Join(list2, ", ")
    fmt.Println(str)
}

Answered By – Adam Smith

Answer Checked By – Marie Seifert (GoLangFix Admin)

Leave a Reply

Your email address will not be published.