Using generics in Go to create a map function (updated)

The generics draft for Go 1.18 changed and my previous post about generics in Go became outdated. Here’s the updated version of it, which you can run in playground.

Given a function that applies a transformation to a single input, a Map function is a known programming pattern to apply that function to an entire array, applying that transformation to all its elements.

In this example, I implemented a generic (of course) Map function to apply a transformation function to a slice of strings. In this case, the input and output have the same type (string). You can run this code in Go playground.

package main

import (
    "fmt"
    "strings"
)

func Map[A, B any](s []A, fn func(a A) B) []B {
    ret := make([]B, len(s))

    for i, input := range s {
        ret[i] = fn(input)
    }

    return ret
}

func main() {
    var (
        slice        = []string{"This\n", "is\n", "some\n", "string"}
        changedSlice = Map(slice, strings.ToUpper)
    )

    fmt.Printf("%v\n", changedSlice)
}

We can use this same Map function to apply a function that transforms that input to a different type. For example, strconv.Itoa can be used here to convert a slice of integers to a slice of strings [playground]:

func main() {
    var (
        integers = []int{1, 12, 42}
        strings  = Map(integers, strconv.Itoa)
    )

    fmt.Printf("%v\n", strings)
}

Links

One thought on “Using generics in Go to create a map function (updated)”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.