06 Arrays, slices and maps

Array

Array can store multiple data of the same type.
Array definition: var Array name [array size] Data type
Access to array elements: array name [subscript], subscript starts from 0
The address of the array can be obtained by array name & array name
each array element address interval is determined according to the type of data in the array, such as: int64 -> 8 int32-> 4
Notes

  1. Once declared, the length of the array is fixed and cannot be changed dynamically
  2. When var arr[] int is defined like this, it actually defines a slice
  3. The elements in the array can be of any data type, but cannot be mixed
  4. After the array is created, if no value is assigned, the default value of the data type is stored by default
  5. When an array is used as a parameter, it is passed by value (assigning a new value). If you want to modify the array in other methods, you need to operate it through pointers.
    6. The length of the array is part of the array. Arrays with inconsistent lengths cannot be passed to the function.

Sample code

func test07(){
    
    
	//数组的声明及使用
	var arr01 [3] int
	arr01[0] = 1
	arr01[1] = 2
	//数组的声明及使用
	arr02 :=[3]int{
    
    1,2,3}
	fmt.Println(arr01,arr02)

	var arr03 = [...]int{
    
    8,9,11,1}
	var arr04 = [...]int{
    
    1:8,2:9,3:11,0:1}
	fmt.Println(arr03,arr04)
	//数组遍历
	for i:=0;i<len(arr01);i++{
    
    
		fmt.Println(i,arr01[i])
	}
	//数组遍历2
	for index,value :=range arr01{
    
    
		fmt.Println(index,value)
	}
}

slice

A slice is a reference to an array, so a slice refers to this type. The mechanism of reference transfer is followed when calling a function. The operation of a slice is the same as an array, but the length of the slice can be changed. It is a variable-length array
definition syntax: var slice Name[] type (the difference with array is that you don't need to specify the length)

important point

  1. From the bottom level, a slice is actually a data structure struct with attributes such as array reference, length, capacity, etc.
  2. The slice length can grow dynamically
    s := arr[0:end] is equivalent to s := arr[:end]
    s := arr[start:len(arr)] is equivalent to s := arr[start:]
    s := arr [0:len(arr)] is equivalent to s := arr:]
  3. After the slice definition is completed, it cannot be used. It must be used to refer to an array or make a space for slice use.
  4. Slicing can continue to slice
  5. Use the append built-in function to dynamically
    append slices. append will create a new array and copy the elements in the original slice to the new slice. The slice is also created. The test result shows that the original slice remains unchanged.
  6. Complete the copy through the copy built-in function, copy the elements in one slice to another slice, and return the number of assigned elements

Sample code

func test08(){
    
    
	var intArr = [...]int{
    
    1,2,3,4,5}
	fmt.Println(intArr)
	//定义切片方式1
	slice := intArr[1:3]
	fmt.Println(len(slice))//长度2
	fmt.Println(cap(slice))//容量4
	fmt.Println(slice) //2,3
	intArr[1] = 7
	fmt.Println(slice) //2,3 //修改原数组后 切边也会变

	s11 := intArr[:]
	s12 := append(s11,5,6,7,8) 
	//append 后产生新的切片,原切片不变
	fmt.Println(s11,s12)
	var ss0 = []int{
    
    1,2,3,4,5}
	var ss1 = make([]int,10)
	ss2 := copy(ss1,ss0)
	fmt.Printf("ss2类型 %T \n",ss2)//int
	fmt.Println("====>",ss0,ss1,ss2)
   
	//定义切片方式2  这种方式可以指定 切片的大小和容量
	// 这种方式定义的切片对应的数组是由make底层去维护,对外不可见
	var s2 [] int = make ([]int ,5,10)
	fmt.Println(len(s2))//5
	fmt.Println(cap(s2))//10
	fmt.Println(s2) //2,3

	//定义切片方式3
   //这种方式和make定义方式类似,
   var s1 []int =[]int{
    
    1,2,3,4,5}
   fmt.Println(cap(s1))//容量4
   fmt.Printf("s1类型 %T,slice类型 %T ,intArr类型%T \n",s1,slice,intArr)
	/*
		方式1 和方式2 的区别,
		方式1 直接引用数组,数组事先存在,程序员可见,修改原数组后 切片也会变
		方式2 make会自动创建一个数组由切片底层维护,程序员不可见
	*/
}

String and slice

  1. The bottom layer of string is a byte array, so it can also be sliced
  2. The string is immutable. If you need to modify the string, you need to first convert the string to a byte array or a rune array, and then rebuild the string after modification.
str01 := "1231231";
strsl := str01[1:]
fmt.Println(strsl)//231231

Two-dimensional array

Element is an array of one-dimensional array is a two-dimensional array
syntax var 数组名[大小][大小]类型such as: var arr[2][2]int
Sample Code

func test09(){
    
    
	//二维数组使用方式1
	//先声明再赋值
	var arr [2][3]int
	arr[0][1] = 10
	fmt.Println("二维数组长度",len(arr))
	fmt.Printf("arr[0]的地址 %p \n",&arr[0])
	fmt.Printf("arr[1]的地址 %p \n",&arr[1])
	//二维数组使用方式2
	//直接初始化 /四种方法
	var arr01 [2][3]int = [2][3]int{
    
    {
    
    1,2,3},{
    
    4,5,6}}
	var arr02 [2][3]int = [...][3]int{
    
    {
    
    1,2,3},{
    
    4,5,6}}
	var arr03 = [2][3]int{
    
    {
    
    1,2,3},{
    
    4,5,6}}
	var arr04 = [...][3]int{
    
    {
    
    1,2,3},{
    
    4,5,6}}
	
	fmt.Println(arr01,arr02,arr03,arr04);

	//遍历
	//双层for循环
	for i:=0;i<len(arr);i++{
    
    
		for j:=0;j<len(arr[i]);j++ {
    
    
			fmt.Println(i,j,"==>",arr[i][j])
		}
	}
	//for range
	for i,v := range arr{
    
    
		for j,v2 := range v{
    
    
			fmt.Println(i,j,"==>",v2)
		}
	}
}

map

Map is a key-value data structure, also known as a field or associative array, similar to the collection
declaration syntax in other programming languagesvar map 变量名 map[keytype]valuetype

The key of map in Golang can be of multiple types, such as bool numbers, strings, pointers, channels, interfaces, structures, and arrays. Normally, keys are strings and ints. Slice, map, and function cannot be used. key, because there is no way to use == to judge.
essentially the same type of key and value, typically digital, string, map, struct
Precautions

  1. map can be automatically expanded
  2. Map is a reference type. Changing the value of the map parameter in the function will affect the content of the map outside the function.

Sample code

func test12(){
    
    
	//map 排序 map是无序的,
	//排序是先将key 排序,再根据排序后的key获取值
	map1 := map[int]int{
    
    
		1:1,
		2:2,
		10:10,
		9:9,
	}
	//直接遍历
	for k,v := range map1{
    
    
		fmt.Println(k,v)
	}

	//排序遍历
	var keys []int
	for k,_ :=range map1{
    
    
		keys = append(keys,k)
	}
	sort.Ints(keys)
	fmt.Println(keys)
	for _,k := range keys{
    
    
		fmt.Println(k,map1[k])
	}
}
func test11(){
    
    
	//map切片
	var monsters []map[string]string
	monsters = make([]map[string]string,1)
	monsters[0] = make(map[string]string,2)
	monsters[0]["name"]="zhansan"
	monsters[0]["age"]="19"
	//由于切片容量为1 所以以下代码会报错
	//panic: runtime error: index out of range
	// monsters[1] = make(map[string]string,2)
	// monsters[1]["name"]="zhansan2"
	// monsters[1]["age"]="192"

	newMonster :=map[string]string{
    
    
		"name":"lisi",
		"age":"32",
	}

	monsters = append(monsters,newMonster)
	fmt.Println(monsters)


}
func test10(){
    
    
	//map 使用方式1
	var m map[string]string
	//声明后必须调用make 分配空间后才可以使用
	m = make(map[string]string,10)
	m["name"] = "zhangsan"
	m["age"] = "20"
	fmt.Println(m,len(m))

	//map使用方式2
	cities := make(map[string]string)
	cities["1"] = "北京"
	cities["2"] = "上海"
	cities["3"] = "天津"
	fmt.Println(cities,len(cities))

	//map使用方式3
	cities2 := map[string]string {
    
    
		"01" : "北京",
		"02" : "上海",
		"03" : "天津",
	}
	cities2["01"] = "北京01" //添加值
	fmt.Println(cities2,len(cities2))
	delete(cities2,"01")//删除值
	fmt.Println(cities2,len(cities2))

	val,ok := cities2["01"]//查询值
	if ok {
    
    
		fmt.Println("存在取值为:",val)
	}else{
    
    
		fmt.Println("值不存在:")
	}
	fmt.Println("=============>遍历")
	for k,v := range cities2{
    
    
		fmt.Println(k,v)
	}


}

Guess you like

Origin blog.csdn.net/zhangxm_qz/article/details/114445537