background
It is required to write a method to return the array after deduplication. The type of the array may beint64
, maybestring
, or other types.
If you distinguish types, you need to rewrite a method for each new type.
Sample code
//Deduplicate the int64 arrayfunc DeDuplicateInt64Slice(array []int64) []int64 { mp := make(map[int64]struct{}) idx := 0 for _, value := range array { if _, ok := mp[value]; ok { continue } array[idx] = value idx = idx + 1 mp[value] = struct{}{} } return array[:idx] } //Deduplicate the string arrayfunc DeDuplicateStringSlice(array []string) []string { mp := make(map[string]struct{}) idx := 0 for _, value := range array { if _, ok := mp[value]; ok { continue } array[idx] = value idx = idx + 1 mp[value] = struct{}{} } return array[:idx] }
Code after using generic implementation
//Deduplicate the arrayfunc DeDuplicateSlice[T any](array []T) []T { mp := make(map[any]struct{}) idx := 0 for _, value := range array { if _, ok := mp[value]; ok { continue } array[idx] = value idx = idx + 1 mp[value] = struct{}{} } return array[:idx] }
in:
T is a type parameter, its usage in the function body is similar to other data types (such asint
Same)
any is a type constraint, where any can be of any type, that is, there is no constraint
// any is an alias for interface{} and is equivalent to interface{} in all ways. type any = interface{}
This is the end of this article about Golang's implementation of using generics to deduplicate arrays. For more related content on Golang array deduplication, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!