GO学习第四天(切片操作、map、rune)

切片的append操作

	arr := [...]int{0, 1, 2, 3, 4, 5, 6}
	s1 := arr[2:5]
	s3 := append(s1, 10)
	s4 := append(s3, 20)
	// 超过arr的cap 系统会重新分配更大数组
	// s5 no longer view arr
	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)
	// 指定len、cap
	s3 := make([]int, 15, 60)
	printSlice(s3)
}

  • 默认值为0

拷贝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      // m2 == nil
	m3 := make(map[string]int) // m3 == empty map

	fmt.Println(m1, m2, m3)

遍历map

	for k, v := range m1 {
		fmt.Println(k, v)
	}
  • mao是无序的,是hash的map

map取值

	fmt.Println("Getting value")
	// 存在ok true,不存在false
	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))

你可能感兴趣的:(GO,GO学习开发)