go Slice切片语法

go Slice 切片语法

切片是一种动态数组,比数组操作灵活,长度不是固定的,可以进行追加和删除。
len()cap() 返回结果可相同和不同。

声明切片

 1//demo_7.go
 2package main
 3
 4import (
 5	"fmt"
 6)
 7
 8func main() {
 9	var sli_1 [] int      //nil 切片
10	fmt.Printf("len=%d cap=%d slice=%v\n",len(sli_1),cap(sli_1),sli_1)
11
12	var sli_2 = [] int {} //空切片
13	fmt.Printf("len=%d cap=%d slice=%v\n",len(sli_1),cap(sli_2),sli_2)
14
15	var sli_3 = [] int {1, 2, 3, 4, 5}
16	fmt.Printf("len=%d cap=%d slice=%v\n",len(sli_3),cap(sli_3),sli_3)
17
18	sli_4 := [] int {1, 2, 3, 4, 5}
19	fmt.Printf("len=%d cap=%d slice=%v\n",len(sli_4),cap(sli_4),sli_4)
20
21	var sli_5 [] int = make([] int, 5, 8)
22	fmt.Printf("len=%d cap=%d slice=%v\n",len(sli_5),cap(sli_5),sli_5)
23
24	sli_6 := make([] int, 5, 9)
25	fmt.Printf("len=%d cap=%d slice=%v\n",len(sli_6),cap(sli_6),sli_6)
26}

截取切片

 1//demo_8.go
 2package main
 3
 4import (
 5	"fmt"
 6)
 7
 8func main() {
 9	sli := [] int {1, 2, 3, 4, 5, 6}
10	fmt.Printf("len=%d cap=%d slice=%v\n",len(sli),cap(sli),sli)
11
12	fmt.Println("sli[1] ==", sli[1])
13	fmt.Println("sli[:] ==", sli[:])
14	fmt.Println("sli[1:] ==", sli[1:])
15	fmt.Println("sli[:4] ==", sli[:4])
16
17	fmt.Println("sli[0:3] ==", sli[0:3])
18	fmt.Printf("len=%d cap=%d slice=%v\n",len(sli[0:3]),cap(sli[0:3]),sli[0:3])
19
20	fmt.Println("sli[0:3:4] ==", sli[0:3:4])
21	fmt.Printf("len=%d cap=%d slice=%v\n",len(sli[0:3:4]),cap(sli[0:3:4]),sli[0:3:4])
22}

追加切片

 1//demo_9.go
 2package main
 3
 4import (
 5	"fmt"
 6)
 7
 8func main() {
 9	sli := [] int {4, 5, 6}
10	fmt.Printf("len=%d cap=%d slice=%v\n",len(sli),cap(sli),sli)
11
12	sli = append(sli, 7)
13	fmt.Printf("len=%d cap=%d slice=%v\n",len(sli),cap(sli),sli)
14
15	sli = append(sli, 8)
16	fmt.Printf("len=%d cap=%d slice=%v\n",len(sli),cap(sli),sli)
17
18	sli = append(sli, 9)
19	fmt.Printf("len=%d cap=%d slice=%v\n",len(sli),cap(sli),sli)
20
21	sli = append(sli, 10)
22	fmt.Printf("len=%d cap=%d slice=%v\n",len(sli),cap(sli),sli)
23}

删除切片

 1//demo_10.go
 2package main
 3
 4import (
 5	"fmt"
 6)
 7
 8func main() {
 9	sli := [] int {1, 2, 3, 4, 5, 6, 7, 8}
10	fmt.Printf("len=%d cap=%d slice=%v\n",len(sli),cap(sli),sli)
11
12	//删除尾部 2 个元素
13	fmt.Printf("len=%d cap=%d slice=%v\n",len(sli[:len(sli)-2]),cap(sli[:len(sli)-2]),sli[:len(sli)-2])
14
15	//删除开头 2 个元素
16	fmt.Printf("len=%d cap=%d slice=%v\n",len(sli[2:]),cap(sli[2:]),sli[2:])
17
18	//删除中间 2 个元素
19	sli = append(sli[:3], sli[3+2:]...)
20	fmt.Printf("len=%d cap=%d slice=%v\n",len(sli),cap(sli),sli)
21}