背景
要求写一个方法,返回去重后的数组。数组的类型可能是 ,也可能是 ,或是其他类型。
如果区分类型的话,每增加一个新的类型都需要重新写一个方法。
示例代码
- //对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 是类型参数,在函数体里的用法跟其他数据类型(如 一样)
any 是类型约束,这里的any可以是任何类型,也就是没有约束 - // any is an alias for interface{} and is equivalent to interface{} in all ways.
- type any = interface{}
复制代码到此这篇关于Golang使用泛型对数组进行去重的实现的文章就介绍到这了,更多相关Golang数组去重内容请搜索晓枫资讯以前的文章或继续浏览下面的相关文章希望大家以后多多支持晓枫资讯!
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |