Friday, May 17, 2024
HomeGolangRely the occurrences of a component in a slice in Go (Golang)

Rely the occurrences of a component in a slice in Go (Golang)



To rely the weather in a slice in Go that fulfill a sure situation, it’s best to make use of Generics out there since Go 1.18. With it, we will create a perform that takes as arguments a slice of any kind and a filter perform that returns true or false for a component of that slice. On this method, we get a common perform that, for any slice, counts the occurrences of components that meet any situation.

bundle principal

import (
    "fmt"
    "strings"
)

func rely[T any](slice []T, f func(T) bool) int {
    rely := 0
    for _, s := vary slice {
        if f(s) {
            rely++
        }
    }
    return rely
}

func principal() {
    s := []string{"ab", "ac", "de", "at", "gfb", "fr"}
    fmt.Println(
        rely(
            s,
            func(x string) bool {
                return strings.Accommodates(x, "a")
            }),
    )

    s2 := []int{1, 2, 3, 4, 5, 6}
    fmt.Println(
        rely(
            s2,
            func(x int) bool {
                return x%3 == 0
            }),
    )
}

As you may see within the instance, the rely() perform accepts a slice of a kind parameter T, whose constraint is any – that’s, it may be a slice of any kind. The physique of the perform is straightforward. If the perform f() returns true for a given slice aspect then the counter rely will increase by 1.

Within the principal(), you may see how versatile the rely() perform is. Within the first case, we put a string slice as an argument and rely the variety of components that include the letter "a". Within the second case, we put an int slice and rely the variety of information divisible by 3. It’s how the magic of Go Generics works. You do not want to write down separate capabilities for every kind – one is ample for all circumstances.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments