package main
import (
"github.com/fatih/set"
)
/**
如何查找出不同切片的差异
*/
func main() {
println("定义两个切片")
s1 :=[] int {1,2,3 }
s2 :=[] int {6,2,3 }
println("创建两个set")
set1 := set.New(set.ThreadSafe)
for e := range s1 {
set1.Add(s1[e])
}
set2 := set.New(set.ThreadSafe)
for e := range s2 {
set2.Add(s2[e])
}
println("对set元素进行循环")
items := set1.List()
for e := range items {
println(items[e].(int))
}
println("从set1中remove掉set2中的元素")
/*
//set2.List()每次生成的是无序的,所以即使坐标一致,每次通过set2.List()[e]取到的值也是不同的
for e := range set2.List() {
set1.Remove(set2.List()[e].(int))
println(set1.String(),set2.List()[e].(int))
println(set1.String(),set2.List()[e].(int))
println(set1.String(),set2.List()[e].(int))
}*/
println("function1:双层循环,暴力比较,参考https://blog.csdn.net/u012210379/article/details/44258677")
println("function2:通过set的remove方法,只循环一遍实现")
set2List := set2.List()
for e := range set2List {
set1.Remove(set2List[e].(int))
println(set1.String(),set2List[e].(int))
}
println("function3:通过map自己实现")
map1:= make(map[int]int)
for e := range s1 {
map1[s1[e]]=s1[e]
}
for e := range s2 {
delete(map1,s2[e])
}
for e := range map1 {
println(map1[e])
}
}
上述列了三个方法
- 双层循环暴力比较
- 借用github set对象remove
- 通过map delete