切片与map类似是引用 需要make进行初始化
make([]int,size,cap)
make 指定slice的长度以及容量
func SliceTest5() {
s1 := make([]int,10,20)
fmt.Println(s1)
}
切片赋值 99为索引,给索引为99的slice赋值
func SliceTest5() {
s1 := []int{99: 1, 1, 2}
fmt.Println(s1)
}
func main() {
SliceTest5()
}
go slice相当于是数组的引用,slice赋值属于浅拷贝如下:
func SliceTest2() {
s1 := []int{1, 2, 3, 4}
s2 := s1
s2[1] = 10
fmt.Printf("s2 contenxt is %+v len is %d,cap is %d\n", s2, len(s2), cap(s2))
fmt.Printf("s1 contenxt is %+v len is %d,cap is %d\n", s1, len(s1), cap(s1))
}
s2 contenxt is [1 10 3 4] len is 4,cap is 4
s1 contenxt is [1 10 3 4] len is 4,cap is 4
s1 s2的第二个元素都变了
如何深拷贝
func SliceTest3() {
s1 := []int{1, 2, 3, 4}
s2 := make([]int, 4, 10)
copy(s2, s1)
s2[1] = 10
fmt.Printf("s2 contenxt is %+v len is %d,cap is %d\n", s2, len(s2), cap(s2))
fmt.Printf("s1 contenxt is %+v len is %d,cap is %d\n", s1, len(s1), cap(s1))
}
只有s2变了
C:\goProject\src\day02>day02.exe
s2 contenxt is [1 10 3 4] len is 4,cap is 10
s1 contenxt is [1 2 3 4] len is 4,cap is 4
切片的首尾范围
0<=lower<=higher<=len(slice)
三个元素lower higher max
slice[lower:higher:max]
0<=lower<=higher<=max
cap为max-lower
对于切片的切片
func SliceTest1() {
s1 := []int{1, 2, 3, 4}
s2 := s1[1:2:3]
fmt.Printf("s2 contenxt is %+v len is %d,cap is %d", s2, len(s2), cap(s2))
}
打印结果
C:\goProject\src\day02>day02.exe
s2 contenxt is [2] len is 1,cap is 2
切片元素删除
func SliceTest4() {
s1 := []int{1, 2, 3, 4}
s2 := s1
s1 = append(s1[:1], s1[2:]...)
fmt.Printf("s1 contenxt is %+v len is %d,cap is %d\n", s1, len(s1), cap(s1))
fmt.Printf("s2 contenxt is %+v len is %d,cap is %d\n", s2, len(s2), cap(s2))
}
func main() {
SliceTest4()
}
C:\goProject\src\day02>day02.exe
s2 contenxt is [1 3 4] len is 3,cap is 4
s2 contenxt is [1 3 4 4] len is 4,cap is 4
append数组追加元素必须要有返回值
func SliceTest4() {
s1 := []int{1, 2, 3, 4}
s2 := make([]int, 4, 10)
fmt.Printf("s1 contenxt is %+v len is %d,cap is %d\n", s1, len(s1), cap(s1))
s1 = append(s1[:1], s2...) //必须有三个点
fmt.Printf("s1 contenxt is %+v len is %d,cap is %d\n", s1, len(s1), cap(s1))
}
由于s1原来只有size 4 cap 4,但是后面追加了4ge元素扩容了为8
s1 contenxt is [1 2 3 4] len is 4,cap is 4
s1 contenxt is [1 0 0 0 0] len is 5,cap is 8