向切片添加元素
arr := […]int{0, 1, 2, 3, 4, 5, 6, 7}
s1 := arr[2:6]
s2 := s1[3:5]
s3 := append(s2, 10)
s4 := append(s3, 11)
s5 := append(s4, 12)
- 添加元素时如果超越cap,系统会重新分配更大的底层数组;
- 由于值传递的关系,必须接收append的返回值;
s = append(s, val)
package main
import "fmt"
func printSlice(s []int) {
fmt.Printf("%v, len=%d, cap=%d\n", s, len(s), cap(s))
}
func main() {
fmt.Println("Creating slice")
var s []int // 定义空切片
for i := 0; i < 100; i++ {
printSlice(s)
s = append(s, 2*i+1)
}
fmt.Println(s)
s1 := []int{2, 4, 6, 8}
printSlice(s1)
s2 := make([]int, 16) // 知道切片元素len,且初始化值为0
s3 := make([]int, 10, 32) // 知道切片元素len和cap,且初始化值为0
printSlice(s2)
printSlice(s3)
// Copying slice
fmt.Println("Copying slice")
copy(s2, s1)
printSlice(s2)
// Deleting elements from slice
fmt.Println("Deleting elements from slice")
s2 = append(s2[:3], s2[4:]...)
printSlice(s2)
// Popping from front
fmt.Println("Popping from front")
front := s2[0]
s2 = s2[1:]
fmt.Println(front)
printSlice(s2)
// Popping from back
fmt.Println("Popping from back")
tail := s2[len(s2)-1]
s2 = s2[:len(s2)-1]
fmt.Println(tail)
printSlice(s2)
}