31

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?

3
  • 1
    what you're looking for is a map function. (as opposed to the map datatype that's analogous to Python's dict)
    – Adam Smith
    Nov 16, 2015 at 0:17
  • Thanks Adam, any idea where i could find them? Is it part of the standard liberaries? I can't find much about it...
    – marczoid
    Nov 16, 2015 at 0:27
  • 4
    I threw an answer up, but googling for "golang map function" will give you more information. The short answer is No, there is no such function in golang
    – Adam Smith
    Nov 16, 2015 at 0:38

6 Answers 6

20

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)
}
17

This is an old question, but was the top hit in my Google search, and I found information that I believe will be helpful to the OP and anyone else who arrives here, looking for the same thing.

There is a shorter way, although you have to write the map function yourself.

In go, func is a type, which allows you to write a function that accepts as input the subject slice and a function, and which iterates over that slice, applying that function.

See the Map function near the bottom of this Go by Example page : https://gobyexample.com/collection-functions

I've included it here for reference:

func Map(vs []string, f func(string) string) []string {
    vsm := make([]string, len(vs))
    for i, v := range vs {
        vsm[i] = f(v)
    }
    return vsm
}

You then call it like so:

fmt.Println(Map(strs, strings.ToUpper))

So, yes: The shorter way you are looking for exists, although it is not built into the language itself.

3
  • 10
    The reason it's not built-in is that Go has no generics (yet?). So you have to write a different Map for each type. Feb 11, 2019 at 15:30
  • After reading the comment above, I was wondering if reflection, interfaces can be used, then I found answer below. Surreal.
    – Anubhav
    Mar 8, 2021 at 19:18
  • 1
    @Anubhav : note that an interface is not the same as a "generic", as it's typically meant in programming languages; the other answer's Map() function has a result of a different type than the input, which might or might not be suitable for specific circumstances; yes, an interface can in some ways be treated like other types, but not in every way, so use the interface-based Map() with that in mind
    – landru27
    Sep 3, 2021 at 12:51
13

I've created a small utility package with Mapand Filter methods now that generics have been introduced in 1.18 :)

https://pkg.go.dev/github.com/sa-/slicefunk

Example usage

package main

import (
    "fmt"

    sf "github.com/sa-/slicefunk"
)

func main() {
    original := []int{1, 2, 3, 4, 5}
    newArray := sf.Map(original, func(item int) int { return item + 1 })
    newArray = sf.Map(newArray, func(item int) int { return item * 3 })
    newArray = sf.Filter(newArray, func(item int) bool { return item%2 == 0 })
    fmt.Println(newArray)
}

8

With go1.18+ you can write a much cleaner generic Map function:

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, e.g:

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) })
0
5

Found a way to define a generic map array function

func Map(t interface{}, f func(interface{}) interface{} ) []interface{} {
    switch reflect.TypeOf(t).Kind() {
    case reflect.Slice:
        s := reflect.ValueOf(t)
        arr := make([]interface{}, s.Len())
        for i := 0; i < s.Len(); i++ {
            arr[i] = f(s.Index(i).Interface())
        }
        return arr
    }
    return nil
}

origin := []int{4,5,3}
newArray := Map(origin, func(item interface{}) interface{} { return item.(int) + 1})
2
  • 2
    That's a bit terse. Using two advanced concepts in go, namely interface{} and reflect explanation should be most welcome. I suppose you 'found' out how to do it, not 'found' it somewhere and copied it.
    – gschenk
    Apr 14, 2020 at 19:18
  • After reading the answer above, I thought of using reflect and interface, and how reflection might slow it down, scroll down a little, and behold.
    – Anubhav
    Mar 8, 2021 at 19:19
2

You can use lo's Map in order to quickly apply a function to all elements. For example, in order to multiply by 2 and convert to string, you can use:

l := lo.Map[int, string]([]int{1, 2, 3, 4}, func(x int, _ int) string { return strconv.Itoa(x * 2) })

Then you can convert back to a comma delimited string like so: strings.Join(l, ",")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.