Monday, May 20, 2024
HomeGolangType a slice of any sort utilizing Generics in Go (Golang)

Type a slice of any sort utilizing Generics in Go (Golang)



Sorting a slice in Go is among the issues that you just used to need to re-write each time there was a brand new slice sort. Generally you ended up with the identical code for 2 differing types. Since Go 1.18, and due to the brand new Generics function, that is now not a difficulty. You’ll be able to write a single common kind perform that works for any sort whose values might be ordered.

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

As an alternative of writing your individual perform, you need to use sorting features slices.Type() and slices.SortFunc() from the golang.org/x/exp/slices bundle, launched along with the Go 1.18.

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

import (
    "fmt"
    "kind"

    "golang.org/x/exp/constraints"
)

func sortSlice[T constraints.Ordered](s []T) {
    kind.Slice(s, func(i, j int) bool {
        return s[i] < s[j]
    })
}

func primary() {
    floatSlice := []float64{2.3, 1.2, 0.2, 51.2}
    sortSlice(floatSlice)
    fmt.Println(floatSlice)

    stringSlice := []string{"z", "a", "b"}
    sortSlice(stringSlice)
    fmt.Println(stringSlice)

    intSlice := []int{0, 3, 2, 1, 6}
    sortSlice(intSlice)
    fmt.Println(intSlice)
}

The one new factor we introduce right here in comparison with our earlier tutorial is the brand new constraints.Ordered constraint within the sortSlice() perform. It ensures that the perform can kind values of any sort supporting the operators <, <=, >=, >. For proof, see the output of the primary() examples, the place three totally different sort slices are sorted with a single perform:

[0.2 1.2 2.3 51.2]
[a b z]
[0 1 2 3 6]

Sorting is a really pure use case for the brand new Generics function. It makes the code concise and introduces just about no complexity.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments