Wednesday, September 18, 2024
HomeGolangGet a slice of keys from any map utilizing Generics in Go...

Get a slice of keys from any map utilizing Generics in Go (Golang)



Earlier than Go 1.18, whenever you needed to tug an inventory of keys from a map in Go, you needed to write code that iterated over the map and added the keys to a slice. Since then, with the brand new Generics function, you possibly can write a single common operate that will get keys from any map and use it everytime you want it. No extra writing code for a selected sort of map 😉.

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

Together with the Go 1.18 launch, the golang.org/x/exp/maps package deal has additionally been launched, with the Keys() operate working the identical because the one under.

 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
package deal principal

import (
    "fmt"
)

func keys[K comparable, V any](m map[K]V) []Ok {
    keys := make([]Ok, 0, len(m))
    for okay := vary m {
        keys = append(keys, okay)
    }
    return keys
}

func principal() {
    vegetableSet := map[string]bool{
        "potato":  true,
        "cabbage": true,
        "carrot":  true,
    }

    fruitRank := map[int]string{
        1: "strawberry",
        2: "raspberry",
        3: "blueberry",
    }

    fmt.Printf("vegetableSet keys: %+vn", keys(vegetableSet))
    fmt.Printf("fruitRank keys: %+vn", keys(fruitRank))
}

The keys() operate takes a map as an argument, during which the keys are of the kind with comparable constraint, and the values, with any constraint. As it’s possible you’ll already know from our earlier tutorial on Generics, the comparable constraint describes sorts whose values will be in contrast, which means that the == and != operators can be utilized on them. The any constraint is equal to interface{} – it accepts any sort, so the values of a map will be something.

The remainder of the operate may be very easy. It returns a slice of keys []Ok, so within the first line of the operate physique, the ensuing slice is created. Discover that it has a capability equal to the scale of the map. Then, in a loop, every map secret is added to the ensuing slice. Operating the instance code with two totally different maps, you get the output:

vegetableSet keys: [potato cabbage carrot]
fruitRank keys: [1 2 3]

And that’s all. Now, with a single keys() operate, you may get an inventory of keys for any map.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments