1.1概述
切片是一种动态数组,比数组操作灵活,长度不是固定的,可以进行追加和删除。
len()
和 cap()
返回结果可相同和不同。
1.2声明切片
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| package main
import ( "fmt" )
func main() { var sli_1 [] int fmt.Printf("len=%d cap=%d slice=%v\n",len(sli_1),cap(sli_1),sli_1)
var sli_2 = [] int {} fmt.Printf("len=%d cap=%d slice=%v\n",len(sli_1),cap(sli_2),sli_2)
var sli_3 = [] int {1, 2, 3, 4, 5} fmt.Printf("len=%d cap=%d slice=%v\n",len(sli_3),cap(sli_3),sli_3)
sli_4 := [] int {1, 2, 3, 4, 5} fmt.Printf("len=%d cap=%d slice=%v\n",len(sli_4),cap(sli_4),sli_4)
var sli_5 [] int = make([] int, 5, 8) fmt.Printf("len=%d cap=%d slice=%v\n",len(sli_5),cap(sli_5),sli_5)
sli_6 := make([] int, 5, 9) fmt.Printf("len=%d cap=%d slice=%v\n",len(sli_6),cap(sli_6),sli_6) }
|
运行结果:
1.3截取切片
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| package main
import ( "fmt" )
func main() { sli := [] int {1, 2, 3, 4, 5, 6} fmt.Printf("len=%d cap=%d slice=%v\n",len(sli),cap(sli),sli)
fmt.Println("sli[1] ==", sli[1]) fmt.Println("sli[:] ==", sli[:]) fmt.Println("sli[1:] ==", sli[1:]) fmt.Println("sli[:4] ==", sli[:4]) fmt.Println("sli[0:3] ==", sli[0:3]) fmt.Printf("len=%d cap=%d slice=%v\n",len(sli[0:3]),cap(sli[0:3]),sli[0:3])
fmt.Println("sli[0:3:4] ==", sli[0:3:4]) fmt.Printf("len=%d cap=%d slice=%v\n",len(sli[0:3:4]),cap(sli[0:3:4]),sli[0:3:4]) }
|
运行结果:
1.4追加切片
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| package main
import ( "fmt" )
func main() { sli := [] int {4, 5, 6} fmt.Printf("len=%d cap=%d slice=%v\n",len(sli),cap(sli),sli)
sli = append(sli, 7) fmt.Printf("len=%d cap=%d slice=%v\n",len(sli),cap(sli),sli)
sli = append(sli, 8) fmt.Printf("len=%d cap=%d slice=%v\n",len(sli),cap(sli),sli)
sli = append(sli, 9) fmt.Printf("len=%d cap=%d slice=%v\n",len(sli),cap(sli),sli)
sli = append(sli, 10) fmt.Printf("len=%d cap=%d slice=%v\n",len(sli),cap(sli),sli) }
|
运行结果:
append 时,容量不够需要扩容时,cap 会翻倍。
1.5删除切片
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| package main
import ( "fmt" )
func main() { sli := [] int {1, 2, 3, 4, 5, 6, 7, 8} fmt.Printf("len=%d cap=%d slice=%v\n",len(sli),cap(sli),sli)
fmt.Printf("len=%d cap=%d slice=%v\n",len(sli[:len(sli)-2]),cap(sli[:len(sli)-2]),sli[:len(sli)-2])
fmt.Printf("len=%d cap=%d slice=%v\n",len(sli[2:]),cap(sli[2:]),sli[2:])
sli = append(sli[:3], sli[3+2:]...) fmt.Printf("len=%d cap=%d slice=%v\n",len(sli),cap(sli),sli) }
|
运行结果: