In one of our previous examples, we created a function that removes duplicate values from a slice in Go. This function, however, needs to be reimplemented each time the slice is of a different type. So, if we had []int
and []string
slices that we wanted to remove duplicates from, so far, we needed two functions: uniqueString()
and uniqueInt()
. But with the release of the Generics in Go 1.18, this is no longer necessary. We can write a single function that will work on any slice where the values satisfy the comparable
constraint.
|
|
Output:
[abc cde efg]
[1 2 3 4]
[{Strawberry 1} {Raspberry 2} {Blueberry 3}]
If you are not already familiar with the basics of Generics in Go, check out our series of articles: Introduction to Go Generics by example.
The function differs from the non-generic version only in that it uses a type parameter T
with the comparable
constraint. This is a built-in constraint that describes any type on which the ==
and !=
operators can be used.
The unique()
function that we created is a universal duplicate removal function that, as you can see in the output of the example, works on any comparable
slice such as []string
, []int
, or a defined struct
slice.