声明
var list1 []int
list1 := make([]int,0)
l2 := []int{1,2,3,4,5}
循环
for i,v := range l2{
fmt.Println(i,v)
}
根据索引查看
print(l2[2])
print(l2[2:4]) 切片
追加
l3 := []int{1,2}
l4 := append(l3,4,5,6,7,8,9,10)
删除元素
//sliceHaiCoder = append(sliceHaiCoder[:index], sliceHaiCoder[index2:]...)
//sliceHaiCoder 要删除元素的切片
//index 要删除的开始索引
//index2 要删除的结束索引
aa := []string{"xiaoming", "gege", "honghong"}
fmt.Println(aa)
aa = append(aa[:0], aa[1:]...)
fmt.Println(aa) //[gege honghong]
修改
value := []int{1,2,3,4,5}
fmt.Println(value)
value[0] = 999
fmt.Println(value) //[999 2 3 4 5]
排序
// 升序
//sort.Ints(intList) 整型排序
//sort.Float64s(float8List) 小数排序
//sort.Strings(stringList) 字符串排序
// 降序
//sort.Sort(sort.Reverse(sort.IntSlice(intList)))
//sort.Sort(sort.Reverse(sort.Float64Slice(float8List)))
dataList := []int{33,55,222,77,99,34,22}
sort.Ints(dataList)
fmt.Println(dataList) //[22 33 34 55 77 99 222]
去重
func RemoveDuplicateElement(stringList []string) []string {
result := make([]string, 0, len(stringList))
temp := map[string]struct{}{}
for _, item := range stringList {
if _, ok := temp[item]; !ok {
temp[item] = struct{}{}
result = append(result, item)
}
}
return result
}
//a := []string{"alex", "egon", "qiqi","qiqi"}
//b := RemoveDuplicateElement(a)
//fmt.Println(b) //[alex egon qiqi]
差集
// l1 := []uint{1,2,3,4,5}
// l2 := []uint{5,6,7,8}
// l3 := DiffArray(l1,l2) [6 7 8]
// 差集 获取l2中有的,l1中没有的
func DiffArray(l1,l2 []uint) []uint {
var l3 []uint
temp := map[uint]struct{}{}
for _,val := range l1 {
if _,ok := temp[val]; !ok {
temp[val] = struct{}{}
}
}
for _,val := range l2 {
if _,ok := temp[val]; !ok {
l3 = append(l3,val)
}
}
return l3
}
交集
//交集
func Intersection(slice1 []uint, slice2 []uint) []uint {
m := make(map[uint]uint)
for _,val := range slice1 {
m[val] =1
}
var ans []uint
for _,val := range slice2 {
times := m[val]
if times != 0 {
ans = append(ans,val)
}
}
return ans
}
//a := []uint{1,2,3,4,5}
//b := []uint{3,4,5,6}
//c := Intersection(a,b)
//fmt.Println(c) //[3 4 5]
并集
func unionSet(slice1 []int,slice2 []int) []int {
m := make(map[int]int)
for _,val := range slice1 {
m[val] = 1
}
for _,val := range slice2 {
times := m[val]
if times == 0 {
slice1 = append(slice1,val)
}
}
return slice1
}
//a := []int{1,2,3,4,5}
//b := []int{3,4,5,6,7}
//c := unionSet(a,b)
//fmt.Println(c) //[1 2 3 4 5 6 7]
字符串切片转字符串
a := []string{"192.168.2.1","192.168.1.1","192.168.3.3"}
fmt.Println(strings.Join(a,",")) //192.168.2.1,192.168.1.1,192.168.3.3
切片重复元素出现次数统计
func SliceRepeatEleCount(slice1 []string) map[string]int {
m1 := make(map[string]int)
for _,v := range slice1 {
if m1[v] != 0 {
m1[v] ++
} else {
m1[v] = 1
}
}
return m1
}