Until now, it was difficult to create in Go the filter()
function known from functional programming, which filters any list of elements according to the boolean value of the predicate. It was possible if you knew the type of the list:
|
|
The main drawback of this solution was that you had to write a separate function for each slice type or use interface{}
and type assertions.
However, with the release of Generics in Go 1.18, we got the ability to write functions where type is a parameter. So now there is no problem writing a filter()
function that operates on a slice of any type.
This article is part of the Introduction to Go Generics series. Go here to see more.
|
|
Output:
[https://bar.com https://gosamples.dev]
[2 4 6]
The filter()
function takes as an argument a slice of type T
. The T
type has the any
constraint, and as you already know from our previous tutorial on Generics, this constraint means that there are no requirements on the type of the slice - it can be anything. The same type T
is used as an argument to the predicate function that checks whether the value should be added to the result. The body of the filter()
function is simple. It performs an iteration over the slice and adds to the result those elements that return true
from the predicate function. As you can see in the output of the example, it works with slices of both string
and int
types, as well as any other type.