Maps is the associated data type built into the go language (sometimes called hashes or dicts in other languages).
Package Mainimport "FMT" Func Main () {//Create an empty dictionary can use built-in functions make: "Made (map[key type] value type)" M: = Make (Map[string]int)//Use classic "name[ Key]=value "To set the value for the key m[" k1 "] = 7m[" K2 "] = 13//with the println output dictionary, it will output all of its key values to the FMT. PRINTLN ("Map:", m)//use "Name[key" to get the value of a key. v1: = m["K1"]fmt. Println ("v1:", v1)//The built-in function returns the number of key-value pairs in the dictionary fmt. Println ("Len:", Len (m))//built-in function delete deletes the value corresponding to a key from the dictionary delete (m, "K2") fmt. PRINTLN ("Map:", m)//To get the value according to the key has an optional second return value;//This return value indicates whether the key exists in the dictionary,//If it is true, returns the corresponding value, or FALSE to return a value of 0// Sometimes it is necessary to use this return value to determine whether the return result is a value or a value of 0//For example, the dictionary does not exist key x corresponding integer value, return 0 value is 0, but just the dictionary has//key y corresponds to the value of 0, this time need that optional return value to determine if the value 0. _, OK: = m["K2"]fmt. Println ("OK:", OK)//You can initialize a dictionary with ": =" at the same time as defined n: = map[string]int{"foo": 1, "bar": 2}fmt. PRINTLN ("Map:", N)}
Output
$ go Run maps.go map:map[k1:7 k2:13]v1: 7len:2map:map[k1:7]prs:falsemap:map[foo:1 Bar:2]
when using FMT. PRINTLN Print output dictionary, the output format is: Map[k:v k:v].
To learn more about dictionaries, see Learning Golang Language (7): Type--Dictionary
Next example: Go by Example:range.
English original
Go by Example:maps