golang slice去重


golang内没有类似python中集合的数据结构,所以去重这样的运算只能自己造轮子了。

随手写了两个示例,一个是string类型的,一个是int类型的

package main

import "fmt"

func main()  {
	s1 := []string{"111", "aaa", "bbb", "ccc", "aaa", "ddd", "ccc"}
	ret := RemoveReplicaSliceString(s1)
	fmt.Println(ret)
	s2 := []int{1 ,2 ,5, 2, 3}
	ret2 := RemoveReplicaSliceInt(s2)
	fmt.Println(ret2)
}


func RemoveReplicaSliceString(slc []string) []string {
	/*
	slice(string类型)元素去重
	*/
	result := make([]string, 0)
	tempMap := make(map[string]bool, len(slc))
	for _, e := range slc{
		if tempMap[e] == false{
			tempMap[e] = true
			result = append(result, e)
		}
	}
	return result
}

func RemoveReplicaSliceInt(slc []int) []int {
	/*
	slice(int类型)元素去重
	*/
	result := make([]int, 0)
	tempMap := make(map[int]bool, len(slc))
	for _, e := range slc{
		if tempMap[e] == false{
			tempMap[e] = true
			result = append(result, e)
		}
	}
	return result
}
输出:
[111 aaa bbb ccc ddd]
[1 2 5 3]


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM