【Golang】使用泛型对数组进行去重

背景:
要求写一个方法,返回去重后的数组。数组的类型可能是int64,也可能是string,或是其他类型。
如果区分类型的话,每增加一个新的类型都需要重新写一个方法。
示例代码:

//对int64数组进行去重
func 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]
}

//对string数组进行去重
func 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]
}

使用泛型实现后的代码

//对数组去重
func 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]
}

其中:
T 是类型参数,在函数体里的用法跟其他数据类型(如int一样)
any 是类型约束,这里的any可以是任何类型,也就是没有约束

// any is an alias for interface{} and is equivalent to interface{} in all ways.
type any = interface{}

你可能感兴趣的:(Go,golang,开发语言,后端)