|
|
package main
|
|
|
|
|
|
import (
|
|
|
"fmt"
|
|
|
"sort"
|
|
|
)
|
|
|
|
|
|
func main() {
|
|
|
var a []string //声明一个字符串切片未初始化
|
|
|
b := []int{} //声明一个整型切片并初始化
|
|
|
c := []bool{true, false} //声明一个整型切片并初始化
|
|
|
fmt.Println(a)
|
|
|
fmt.Println(b)
|
|
|
fmt.Println(c)
|
|
|
fmt.Println(a == nil)
|
|
|
fmt.Println("===切片===")
|
|
|
|
|
|
test := []int{5, 4, 3, 8, 6}
|
|
|
testSlice1 := test[1:3]
|
|
|
fmt.Printf("slice1:%v, len: %v, caps: %v\n", testSlice1, len(testSlice1), cap(testSlice1))
|
|
|
|
|
|
//切片再切片的结果起始位置在上一个切片的起始位置,high上限未原始数组的容量
|
|
|
//我的理解:a [1,2,3,4,5,6]
|
|
|
// 切片:b=a[2,4] = [3,4] length=4-2=2 capacity=数组[3,4,5,6]的容量=4
|
|
|
testSlice2 := testSlice1[0:4]
|
|
|
fmt.Printf("slice2:%v, len: %v, caps: %v\n", testSlice2, len(testSlice2), cap(testSlice2))
|
|
|
|
|
|
//capacity=max-low=3 length=high-low=2
|
|
|
testSlice3 := test[2:4:5]
|
|
|
fmt.Printf("slice3:%v, len:%v, cap:%v\n", testSlice3, len(testSlice3), cap(testSlice3))
|
|
|
|
|
|
fmt.Println("===make===")
|
|
|
|
|
|
sliceMake := make([]bool, 2, 10)
|
|
|
fmt.Printf("make: %v, len: %v, cap: %v\n", sliceMake, len(sliceMake), cap(sliceMake))
|
|
|
|
|
|
fmt.Println("===赋值===")
|
|
|
|
|
|
s1 := make([]int, 3) //[0 0 0]
|
|
|
s2 := s1 //将s1直接赋值给s2,s1和s2共用一个底层数组
|
|
|
s2[0] = 100
|
|
|
fmt.Println(s1) //[100 0 0]
|
|
|
fmt.Println(s2) //[100 0 0]
|
|
|
|
|
|
s11 := []int{1, 3, 5, 7, 9, 0, 2, 4, 6, 8}
|
|
|
s12 := make([]int, 5, 5)
|
|
|
copy(s12, s11) //数据复制到另一片空间
|
|
|
s11[0] = 100
|
|
|
fmt.Println(s11)
|
|
|
fmt.Println(s12)
|
|
|
|
|
|
fmt.Println("===遍历===")
|
|
|
slice4range := []int{1, 3, 5, 6, 4, 2}
|
|
|
for i := 0; i < len(slice4range); i++ {
|
|
|
fmt.Printf("%v ", slice4range[i])
|
|
|
}
|
|
|
fmt.Println()
|
|
|
for index, value := range slice4range {
|
|
|
fmt.Println(index, value)
|
|
|
}
|
|
|
|
|
|
fmt.Println("===删除===")
|
|
|
sliceDel := []int{1, 2, 3, 4, 5, 6}
|
|
|
sliceDel = append(sliceDel[:2], sliceDel[3:]...)
|
|
|
fmt.Println(sliceDel)
|
|
|
|
|
|
var m = make([]string, 5, 10)
|
|
|
for i := 0; i < 10; i++ {
|
|
|
m = append(m, fmt.Sprintf("%v", i))
|
|
|
}
|
|
|
fmt.Println(m)
|
|
|
|
|
|
var mm = [...]int{3, 7, 8, 9, 1}
|
|
|
ms := mm[0:len(mm)]
|
|
|
|
|
|
sort.Slice(ms, func(i, j int) bool {
|
|
|
return ms[i] < ms[j]
|
|
|
})
|
|
|
|
|
|
fmt.Printf("Sort: %v\n%v\n", mm, ms)
|
|
|
}
|