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]