"Go Language" "10" Go language map

Source: Internet
Author: User

There is a map in the go language, in addition to arrays and slices, and the map estimates that everyone is not unfamiliar, because in the Java, C + + and other languages have its figure, it in the form of <key,value> for programmers to provide services.

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/5B/42/wKioL1UEBN3BISr0AACD7FzA4IA979.jpg "title=" Map.png "alt=" Wkiol1uebn3bisr0aacd7fza4ia979.jpg "/>

You can also see that six city information is stored in memory, where key is the city telephone area code and value is the city name. The City telephone area code (key) is unique, so that the programmer to the city name (value) to increase, delete, change, check and other operations; There is also a certain association between <key,value>, that is, the arrow in the diagram, But this association does not need special attention to the beginner of Go language.


First, map declaration, initialization and assignment

1. Declaration format: var variable name map[key value type]value value type

For example:

var cityMap map[string]string

var employeemap map[int]string

var boolmap map[string]bool


2. Map initialization

var cityMap map[string]string = map[string]string{"010": "Beijing", "022": "Tianjin", "021": "Shanghai", "020": "Guangzhou", "0755": "Shenzhen", "0571" : "Hangzhou"}

var employeemap map[int]string = map[int]string{1: "Boss", 2: "Manager", 3: "Employee"}

var boolmap map[string]bool = map[string]bool{"North Korea": True, "Japan": false, "Iran": True, "China": true, "Russia": false}


Of course, if this sentence is too long, it can be simplified as follows:

var cityMap = map[string]string{"010": "Beijing", "022": "Tianjin", "021": "Shanghai", "020": "Guangzhou", "0755": "Shenzhen", "0571": "Hangzhou"}

var employeemap = map[int]string{1: "Boss", 2: "Manager", 3: "Employee"}

var boolmap = map[string]bool{"North Korea": True, "Japan": false, "Iran": True, "China": true, "Russia": false}


This can also be simplified:

CityMap: = map[string]string{"010": "Beijing", "022": "Tianjin", "021": "Shanghai", "020": "Guangzhou", "0755": "Shenzhen", "0571": "Hangzhou"}

Employeemap: = map[int]string{1: "Boss", 2: "Manager", 3: "Employee"}

Boolmap: = map[string]bool{"North Korea": True, "Japan": false, "Iran": True, "China": true, "Russia": false}


If the above two simplification methods or feel too long, you can use the method of assignment

3. Map Assignment

var cityMap map[string]string //Declaration CITYMAP Variable

var employeemap map[int]string //Declaration Employeemap Variable

var boolmap map[string]bool //Declaration Boolmap Variable


CityMap = map[string]string{} //Initialize variable CityMap

citymap["010"] = "Beijing" //Assign value to variable CityMap

citymap["022"] = "Tianjin"

citymap["021"] = "Shanghai"

Citymap["020"] = "Guangzhou"

citymap["0755"] = "Shenzhen"

citymap["0571" = "Hangzhou"


Employeemap = map[int]string{} //Initialize variable Employeemap

EMPLOYEEMAP[1] = "Boss" //Assign value to variable Employeemap

EMPLOYEEMAP[2] = "Manager"

EMPLOYEEMAP[3] = "Employee"


Boolmap = map[string]bool{} //Initialize variable Boolmap

boolmap["North Korea"] = true //Assign value to variable Boolmap

Boolmap["Japan"] = False

boolmap["Iran"] = True

boolmap["China"] = True

Boolmap["Russia"] = False


Ii. creating and traversing a map

1. Create a map with make

In addition to declaring the map in the way above, you can create a new map like slice with the go language built-in function make (). The above example can be rewritten as follows:

CityMap: = Make (map[string]string)

Employeemap: = Make (map[int]string)

Boolmap: = Make (Map[string]bool)


Map creation is similar to the creation of slice, and can also specify the capacity of the map at creation time

CityMap: = Make (map[string]string, 6)

Employeemap: = Make (map[int]string, 3)

Boolmap: = Make (Map[string]bool, 5)


2. Traverse Map

Here's an example of how to traverse a map: (1) Create a map and assign a value (2) traverse map (3) Delete a city with a telephone area code of 022

Create a map and assign a value

CityMap: = Make (map[string]string, 6)

citymap["010" = "Beijing"

citymap["022"] = "Tianjin"

citymap["021"] = "Shanghai"

Citymap["020"] = "Guangzhou"

citymap["0755"] = "Shenzhen"

citymap["0571" = "Hangzhou"

Fmt. Println (CITYMAP)


Traverse Map

For k, _: = Range CityMap {

Delete a city with a telephone area code of 022

if k = = "022" {

Delete (CityMap, k)

}

}

Fmt. Println (CITYMAP)

The result of the program operation is:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/5B/49/wKiom1UEKiXQOiNSAACyZRkOg8I024.jpg "title=" Result.png "alt=" Wkiom1uekixqoinsaacyzrkog8i024.jpg "/>


3. Multiple return values

The go language is very different from Java, C + + and so on: multiple return values , go language functions can have multiple return values, this feature makes code writing more concise

For key, Value: = Range citymap{

Slightly

}

When using Traverse Citymap, the <key,value> value between the map is returned, the programmer can use the key value, or use value, assuming the programmer does not need value, you can change the value to _ as in the example above.

For key, _ : = Range citymap{

Slightly

}


Third, map considerations

1. Map stores data in <key, value> form, where key must be a type that supports the = = or! = operation, not a map, slice, or function

2, map lookup faster than linear search speed

3. Determine the number of map elements using the Len () function instead of size ()

4, go language use the built-in delete () function to delete the elements in the map, the first parameter is a map, the second parameter is a key in the map, if the key does not exist, then nothing happens, but if the key is set to nil, then the deletion will throw an exception


Iv. value in Map

The value type in map can be either an underlying type or a composite type, or it can be a struct


1, the value type is the structure body

"Value type is a storage model for structs":

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/5B/4A/wKiom1UEPNHT9NYiAACXJ8DSqMY393.jpg "title=" Storage model. png "alt=" wkiom1uepnht9nyiaacxj8dsqmy393.jpg "/>


"Program Implementation":

Define Structure body

Type persion struct {

Name, Phone string

Age int

}

Creates a map whose value type is persion

Persionmap: = Make (Map[string]persion)

Assigns a value to the element in map whose key type is a string and the value type is persion

persionmap["123456"] = persion{name: "Corrected brother", Age:35, Phone: "13581887557"}

persionmap["789012"] = Persion{name: "Bare running brother", Age:5, Phone: "None"}

Traverse map to print out persion information

For _, Value: = Range Persionmap {

Fmt. Println ("Name:", value.) Name, "\ t Age:", value. Age, "\ t phone:", value. Phone)

}

"Run Results":

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/5B/44/wKioL1UENgmiWtIyAACBrIpHhYc160.jpg "title=" The type is struct. png "alt=" wkiol1uengmiwtiyaacbriphhyc160.jpg "/>


2. The value type is map

"Program Implementation":

Create a map whose value type is map

Persionmap: = Make (map[string]map[string]string)


persionmap["123456"] = map[string]string{"name": "Corrected brother", "phone": "13581887557", "Age": "35"}

persionmap["789012"] = map[string]string{"name": "Bare running brother", "phone": "None", "Age": "5"}


Traverse map to print out persion information

For _, Value: = Range Persionmap {

Fmt. Println ("Name:", value["name"], "\ t Age:", value["ages"], "\ t phone:", value["phone"])

}

"Run Results":

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/5B/44/wKioL1UENgmiWtIyAACBrIpHhYc160.jpg "title=" The type is struct. png "alt=" wkiol1uengmiwtiyaacbriphhyc160.jpg "/>

"description":

When the Vlaue type is map, it is similar to the previous value type of struct persion, except that the value of the health value pair is a map, but if you do not find the difference, the map appears as generics, as in this example, although the value of age is integer, but because of the generic requirements, The age here must be enclosed in double quotes.

This article is from the "Green Guest" blog, please be sure to keep this source http://qingkechina.blog.51cto.com/5552198/1620429

"Go Language" "10" Go language map

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.