Code Demo
PackageMainImport "FMT"funcMain () {m: = Make(Map[string]int) m["K1"] =7m["K2"] = -Fmt. Println ("Map:", m) V1: = m["K1"] FMT. Println ("v1:", v1) fmt. Println ("Len:",Len(m))Delete(M,"K2") FMT. Println ("Map:", M) _, PRS: = m["K2"] FMT. Println ("PRS:", PRS) N: =Map[string]int{"foo":1,"Bar":2} FMT. Println ("Map", N)}
Code Run Results
Map:map[k1:7 K2:13]
V1:7
Len:2
Map:map[k1:7]
Prs:false
Map Map[foo:1 Bar:2]
Code interpretation:
- Maps is the data type built into the go language, as well as a dictionary or map.
- Create an empty dictionary using make (Map[key-type]val-type)
- To set a key-value pair, use the name[key] = value method
- With FMT. Println Way to print out all the key values in the dictionary
- Use Name[key] to get a value
- With the built-in method Len can return the number of key-value pairs, which is the length of the dictionary
- Use the built-in method delete to remove a key value pair from the dictionary
- The second return value can be returned if the key is in this dictionary, which can be used to eliminate the key does not exist or there is a 0 value ambiguity, when the first return value is not required, you can use the space character "_" to represent
- You can also declare and initialize a dictionary on a single line, such as "N: = map[string]int{" foo ": 1," Bar ": 2}"
Maps maps (dictionaries) in 010_go languages