Cookies management by TermsFeed Cookie Consent

🦾 Create a slice 'map' function using Generics in Go

introduction generics generics-intro

Please consider supporting us by disabling your ad blocker

The map() function is another functional programming paradigm that can be easily implemented in Go thanks to the new Generics feature. It works by applying a function that takes a single slice element as an argument, transforms it, and returns output value, where the types taken and returned need not be the same. For example, you can use the map() function to convert string to int slice; or format each element of the string slice, without changing the output type. Such different use cases are not problematic when using Generics as the map() can run on any input and output types.

This article is part of the Introduction to Go Generics series. Go here to see more.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package main

import (
    "fmt"
    "math"
    "strconv"
)

func mapSlice[T any, M any](a []T, f func(T) M) []M {
    n := make([]M, len(a))
    for i, e := range a {
        n[i] = f(e)
    }
    return n
}

func main() {
    numbers := []float64{4, 9, 16, 25}

    newNumbers := mapSlice(numbers, math.Sqrt)
    fmt.Println(newNumbers)

    words := []string{"a", "b", "c", "d"}
    quoted := mapSlice(words, func(s string) string {
        return "\"" + s + "\""
    })
    fmt.Println(quoted)

    stringPowNumbers := mapSlice(numbers, func(n float64) string {
        return strconv.FormatFloat(math.Pow(n, 2), 'f', -1, 64)
    })
    fmt.Println(stringPowNumbers)
}

Output:

[2 3 4 5]
["a" "b" "c" "d"]
[16 81 256 625]

The mapSlice() function (we use the name mapSlice() because map is Golang keyword) takes two type parameters. T is the type of the input slice, and M is the type of the output slice. Both of them can be of any type. The function also takes two arguments: the slice a and the function f that transforms each of its elements. Notice that this function converts the value of the input type T into the output type M. The mapSlice() works by creating a new output slice of the same length as the input and transforming each element of the input slice into the output slice in a loop by using the f function. This simple code is enough to get a universal map() function that, as the example shows, can square float64 elements of a slice, format strings by adding quotes, or raise numbers to a power.


Thank you for being on our site 😊. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.

Have a great day!

🗑️ Remove duplicates from any slice using Generics in Go

Learn how to create a slice with unique values using Generics
introduction slice generics generics-intro

🔉 Reduce function using Generics in Go

Learn how to define a function to accumulate slice values using Generics
introduction generics generics-intro

💂 Filter a slice using Generics in Go

Learn how to remove elements from a slice that do not meet a certain condition using Generics
introduction generics generics-intro