We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
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:
func Unique[T comparable](s []T) []T {
inResult := make(map[T]bool)
var result []T
for _, str := range s {
if _, ok := inResult[str]; !ok {
inResult[str] = true
result = append(result, str)
}
}
return result
}
This is much easier than having to create the same function for each type you want to support.
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.