切片的append操作
arr := [...]int{0, 1, 2, 3, 4, 5, 6}
s1 := arr[2:5]
s3 := append(s1, 10)
s4 := append(s3, 20)
s5 := append(s4, 30)
fmt.Println("s3,s4,s5=", s3, s4, s5)
s4[0] = 200
s3[1] = 600
s5[1] = 500
fmt.Println("s3,s4,s5=", s3, s4, s5)
fmt.Println("arr=", arr)
- s3.s4是arr的view,append后没有超过arr的cap。直接修改原数组的值
- s5不再是arr的view,系统会在底层重新分配一个长度更长的数组
- 因为传值,所以必须有变量接
- s = append(s, val)
直接申明切片
func printSlice(s []int) {
fmt.Printf("%v,len=%d,cap=%d\n", s, len(s), cap(s))
}
func main() {
var s []int
for i := 0; i < 50; i++ {
printSlice(s)
s = append(s, i*2)
}
s1 := []int{1, 2, 3}
printSlice(s1)
s2 := make([]int, 15)
printSlice(s2)
s3 := make([]int, 15, 60)
printSlice(s3)
}
拷贝slice
fmt.Println("Copy slice:")
copy(s2, s1)
fmt.Println(s2)
删除slice元素
fmt.Println("Popping slice element")
s2 = append(s2[:3], s2[4:]...)
fmt.Println(s2)
fmt.Println("Popping slice element from front")
front := s2[0]
s2 = s2[1:]
fmt.Println(front, s2)
fmt.Println("Popping slice element from back")
back := s2[len(s2)-1]
s2 = s2[:len(s2)-1]
fmt.Println(back, s2)
map定义
m1 := map[string]string{
"grade": "one",
}
var m2 map[string]int
m3 := make(map[string]int)
fmt.Println(m1, m2, m3)
遍历map
for k, v := range m1 {
fmt.Println(k, v)
}
map取值
fmt.Println("Getting value")
if name, ok := m1["grade"]; ok {
fmt.Println(name)
} else {
fmt.Println("key is not found.")
}
map删除元素
fmt.Println("Delete value")
name, ok := m1["grade"]
fmt.Println(name, ok)
delete(m1, "grade")
name, ok = m1["grade"]
fmt.Println(name, ok)
rune
fmt.Println(len(str))
fmt.Println(utf8.RuneCountInString(str))