Wednesday, May 8, 2024
HomeGolangCreate a slice 'map' perform utilizing Generics in Go (Golang)

Create a slice ‘map’ perform utilizing Generics in Go (Golang)



The map() perform is one other useful programming paradigm that may be simply applied in Go due to the brand new Generics characteristic. It really works by making use of a perform that takes a single slice aspect as an argument, transforms it, and returns output worth, the place the kinds taken and returned needn’t be the identical. For instance, you need to use the map() perform to transform string to int
slice; or format every aspect of the string slice, with out altering the output kind. Such completely different use instances will not be problematic when utilizing Generics because the map() can run on any enter and output sorts.

This text is a part of the Introduction to Go Generics sequence. Go right here to see extra.

 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
bundle important

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 := vary a {
        n[i] = f(e)
    }
    return n
}

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

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

    phrases := []string{"a", "b", "c", "d"}
    quoted := mapSlice(phrases, 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() perform (we use the identify mapSlice() as a result of map is Golang key phrase) takes two kind parameters. T is the kind of the enter slice, and M is the kind of the output slice. Each of them may be of any kind. The perform additionally takes two arguments: the slice a and the perform f that transforms every of its parts. Discover that this perform converts the worth of the enter kind T into the output kind M. The mapSlice() works by creating a brand new output slice of the identical size because the enter and remodeling every aspect of the enter slice into the output slice in a loop by utilizing the f perform. This straightforward code is sufficient to get a common map() perform that, as the instance reveals, can sq. float64 parts of a slice, format strings by including quotes, or increase numbers to an influence.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments