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.
|
|
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.