map is an unsorted collection of key-value pairs, similar to the concept of a dictionary in Python. Its format is map[keyType]valueType, which is a key-value hash structure. The reading and setting of map are also similar to slice, and are operated through key, except that the index of slice can only be int type, while map has many more types, including int, string and all fully defined == and != The type of operation.
The syntax for declaring a map is as follows:
var map变量名 map[key] value
Among them: key is the key type, value is the value type
For example: value can not only be annotation data type, but also self- Define the data type
var numbers map[string] int var myMap map[string] personInfo
personInfo as a custom structure to store personal information, defined as follows
type personInfo struct { ID string Name string Address string }
map initialization:
1. Direct initialization (creation)
rating := map[string] float32 {"C":5, "Go":4.5, "Python":4.5, "C++":2 } myMap := map[string] personInfo{"1234": personInfo{"1", "Jack", "Room 101,..."},}
2. Initialization (creation) through make
The built-in function make() provided by the Go language can be used to flexibly create maps.
Created a map with key type string and value type int
numbers := make(map[string] int)
Created a map with key type string and value type personInfo
myMap = make(map[string] personInfo)
can also be used Choose whether to specify the initial storage capacity of the map when creating it. For example, create a map with an initial storage capacity of 5
myMap = make(map[string] personInfo, 5)
After creation, the initialization is as follows:
numbers["one"] = 1 myMap["1234"] = personInfo{"1", "Jack", "Room 101,..."}
For more golang knowledge, please pay attentiongolang tutorial column.
The above is the detailed content of How to create map in golang. For more information, please follow other related articles on the PHP Chinese website!