Using Generics and Predicates in Go 😊

Vijesh
2 min readJun 15, 2023

--

Go is a powerful programming language that has recently introduced support for generics. This allows developers to write code that can work with any of a set of types provided by calling code, without explicitly providing specific data types. In this post, we’ll explore how to use generics and predicates in Go to write more flexible and reusable code.

First, let’s take a look at an example of a generic function in Go:

package main

import "fmt"

type Predicate[A any] func(A) bool

func Filter[A any](input []A, pred Predicate[A]) []A {
output := []A{}
for _, element := range input {
if pred(element) {
output = append(output, element)
}
}
return output
}

func great(a int) bool {
return a > 5
}

func main() {
input := []int{1, 1, 3, 5, 8, 13, 21, 34, 55}
output := Filter(input, great)
fmt.Printf("%v", output)
}

In this example, we define a generic Filter function that takes an input slice of any type A, and a predicate function pred of type Predicate[A]. The Filter function returns a new slice containing only the elements from the input slice for which the predicate function returns true.

The Predicate[A] type is defined as a function that takes an argument of type A and returns a boolean value. This allows us to pass any function that matches this signature as the pred argument to the Filter function.

In the main function, we define an example predicate function great that takes an integer argument and returns true if the argument is greater than 5. We then use this function as the pred argument when calling the Filter function on an input slice of integers.

The result is a new slice containing only the elements from the input slice that are greater than 5.

This is just one example of how generics and predicates can be used in Go to write more flexible and reusable code. By defining functions and types that can work with any set of types provided by calling code, developers can write more modular and maintainable code.

Thank you for reading my blog. Hope you learned something new today 🥳

--

--

Vijesh

Am a freelancer as a web developer, keeps learning new things