This is a creation in Article, where the information may have evolved or changed.
Directory
-
- Map
- Create a Map
- Setter and Getter
- Size
- Delete an element
- Map nesting
- Check if key exists
- Traverse
Summary
Create Map,make,setter,getter,size,delete, check the existence of keys, traverse
Map
Create a Map
Define and then initialize
varmap[int]stringmap[int]string{} //m1 map[]
Using the Make function
Format is
make([keyType]valueType, cap)
Capacity can be omitted
varmap[int]stringmake(map[int]string)
Use shorthand
make(map[int]string)
Setter and Getter
Setter
m3[1"a" //m3 map[1:a]
The "1" Here is a key, not an index
Getter
a := m3[1]b := m3[2]fmt.Println("a"//a afmt.Println("b"//b
Returns NULL when a nonexistent key is obtained
Size
varlen(m3)
Delete an element
delete(m3, 1)fmt.Println("a", a) //a afmt.Println("m3"//m3 map[]
Map nesting
The Value of a map is another map
varMMap[int]Map[int]string= Make(Map[int]Map[int]string) m[1] = Make(Map[int]string) m[1][1] ="a"Fmt. Println ("M", m)//m Map[1:map[1:a]]Fmt. Println ("m[1]"M[1])//m[1] map[1:a]
Check if key exists
When you use shorthand to return multiple values at the same time, the second parameter that the map returns is a Boolean value that indicates whether the key exists
m3[1"a"m3[2"b"v, exist := m3[3] //第二个参数为布尔值,表示键是否存在fmt.Println("v", v) //vfmt.Println("exist"//exist false
Traverse
forrange m3 { fmt.Println(k, v)}
where k is the key, if you want to ignore the use of K can use the placeholder "_"
//Ignore value for k: = range w {fmt. Print (k)}//ignore key for _, V: = range w {fmt. Print (v)}