In the previous section, we learned how to use map.
map can be defined in two ways, one is the standard way, assigning a value when declaring, and the other is make.
package main import "fmt" func main() { var stu1 = map[string]string{ "Name": "张三", "Age": "18", "height": "188", //每行都要以,结尾, } stu2:=make(map[string]string,10) stu2["Name"] = "李四" stu2["Age"] = "170" stu2["height"] = "109" fmt.Println(stu1,stu2) //map[Age:18 Name:张三 height:188] map[Age:170 Name:李四 height:109] }
I don’t know if you have found a problem with the map we are currently storing It seems that only one can be stored.
Generally speaking, I should have a list that stores student information one by one.
Pseudocode:
var student_list = [张三的信息,李四的信息,王五的信息,...]
But after playing for so long, there are still single pieces of information. It's bad, it's harmful.
We know the slice, is defined like this.
var names []string var names = []string{} var names = make([]string,0,10)
In the above, the lists are saved with basic types, strings, numbers, etc.
For something exciting, store the map directly in the list.
伪代码
var names = []map[string]string{} //注意:map[string]string{}是切片里面值的类型,这个切片里面的每个值都是map类型
示例代码
package main import "fmt" func main() { //定义个类型是map的列表 var names = []map[string]string{} var name1 = map[string]string{ "Name": "张三", "Age": "18", } var name2 = map[string]string{ "Name": "李四", "Age": "22", } names = append(names, name1, name2) //向列表中添加map fmt.Println(names) //[map[Age:18 Name:张三] map[Age:22 Name:李四]] }
图解
在以往的操作中,我们的map的key和value都是一个值。
那像一个人的爱好了,生活习惯了,等,都不止一个,所以,在map中,map的值(value),应该能保存多个才对。
代码
package main import "fmt" func main() { //map中,value为切片类型 var person_hoppy = map[string][]string{} person_hoppy["hoppy"] = []string{"吃", "喝", "拉", "撒"} fmt.Println(person_hoppy)//map[hoppy:[吃 喝 拉 撒]] }
图解
注:在map中,key只能是固定值,因为要通过key找值,所以key不能修改,value可以是任意类型。
The above is the detailed content of Go language basics map supplement. For more information, please follow other related articles on the PHP Chinese website!