#development #golang #pattern

Initially, I was a bit sceptic when generics where introduced in Golang, but I'm slowly starting to love them.

Recently, I need to filter a slice and remove all duplicates. With generics, this is a breeze:

 1func Unique[T comparable](s []T) []T {
 2    inResult := make(map[T]bool)
 3    var result []T
 4    for _, str := range s {
 5        if _, ok := inResult[str]; !ok {
 6            inResult[str] = true
 7            result = append(result, str)
 8        }
 9    }
10    return result
11}

This is much easier than having to create the same function for each type you want to support.