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

背景:

要求写一个方法,返回去重后的数组。数组的类型可能是int64,也可能是string,或是其他类型。

如果区分类型的话,每增加一个新的类型都需要重新写一个方法。
示例代码:

go 复制代码
//对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]
}

使用泛型实现后的代码

go 复制代码
//对数组去重
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{}

相关推荐
Boilermaker199239 分钟前
【Java EE】Mybatis-Plus
java·开发语言·java-ee
aramae1 小时前
C++ -- STL -- vector
开发语言·c++·笔记·后端·visual studio
Tony小周1 小时前
实现一个点击输入框可以弹出的数字软键盘控件 qt 5.12
开发语言·数据库·qt
lifallen1 小时前
Paimon 原子提交实现
java·大数据·数据结构·数据库·后端·算法
lixzest1 小时前
C++ Lambda 表达式详解
服务器·开发语言·c++·算法
沉默媛1 小时前
如何安装python以及jupyter notebook
开发语言·python·jupyter
舒一笑2 小时前
PandaCoder重大产品更新-引入Jenkinsfile文件支持
后端·程序员·intellij idea
_Chipen2 小时前
C++基础问题
开发语言·c++
PetterHillWater2 小时前
AI编程之CodeBuddy的小试
后端·aigc
止观止3 小时前
JavaScript对象创建9大核心技术解析
开发语言·javascript·ecmascript