Golang learning road-map slice

basic introduction

If the data type of the slice is map, we call it slice of map, and map slice, so that the number of maps can be dynamically changed when used.

Case presentation

Requirements: Use a map to record the student's name and age, that is, a student corresponds to a map, and the number of students can be dynamically increased.

package main

import(
	"fmt"
)

func main(){
    
    
	
	var stu []map[string]string
	stu = make([]map[string]string, 1)
	
	//增加第一个学生的信息
	if stu[0] == nil{
    
    
		stu[0] = make(map[string]string)
		stu[0]["name"] = "Casey"
		stu[0]["age"] = "18"
	}
	//下面这个写法越界
	// if stu[1] == nil{
    
    
	// 	stu[1] = make(map[string]string)
	// 	stu[1]["name"] = "Jerry"
	// 	stu[1]["age"] = "28"
	// }
	//我们需要使用到切片的append函数,可以动态增加学生
	student := map[string]string{
    
    
		"name" : "Jerry",
		"age" : "28",
	}
    stu = append(stu,student)
	fmt.Println(stu)
}

operation result:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44736475/article/details/114154460