Go Language Practical Notes (vi) | Go Map

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

"Go language Combat" reading notes, not to be continued, welcome to sweep code attention flysnow_org to the public, the first time to see follow-up notes.

I think it's too hard to translate the map into maps, so I'll use the English map in this article.

A map is a data structure that is a collection that stores a series of unordered key-value pairs. It is based on key storage, like an index, which is also a powerful place for maps to quickly and quickly retrieve data, and keys to the values associated with that key.

Internal implementation

Map is to give a hash list to achieve, is what we often say the hash table, so each time we iterate map, the printed key and value is unordered, each iteration is different, even if we exist in a certain order.

The hash list of the map contains a set of buckets, and each time you store and look up a key-value pair, you select a bucket first. How do you choose a bucket? is to pass the specified key to the hash function, it can be indexed to the corresponding bucket, and then find the corresponding key value.

The advantage of this way is that the more data stored, the more uniform the distribution of the index, so we access the key value of the speed of the more quickly, of course, the details of the storage there are many, we can refer to the knowledge of the hash, here we just remember that the map is stored in the unordered set of key-value pairs .

Declaration and initialization

Map creation has make functions, map literals. makefunction We have created slices with it, and in addition, it can flood to create a map.

1
dict:=make (map[string]int)

In the example, a map with a key type of string value type is created int . Now that it's created, the map is empty, there's nothing in it, and we're going to store a key-value pair.

12
 Make (map[string]int) dict["Zhang San"

Stores a key value of Zhang San, value 43, for the data.

There is also a way to create and initialize a map using the map literal, which we can do equally for the above example.

1
Map [string] int {"Zhang San":

Using a curly brace for initialization, key-value pairs are : separated by separating, if you want to initialize multiple key-value pairs simultaneously, use commas to split them.

1
Map [string] int {"Zhang San":"John Doe":

Of course we can not specify any key-value pairs, that is, an empty map.

1
Map [string] int {}

In any case, use the map's literal creation to be sure to bring braces. What if we were to create a nil map? nilmap is uninitialized, so we can declare only one variable, either using the map literal, or using the make function to allocate memory.

1
var Map [string] int

That's fine, but we can't manipulate the store key-value pairs, but we have to initialize them before we can, for example, use a make function to open a piece of memory that can store the data, that is, initialize.

1234
var Map [string] int  Make (map[string]int) dict["Zhang San"to the FMT. Println (Dict)

The key of a map can be any value, the type of the key can be a built-in type, or it can be a struct type, but in any case, this key can be == compared using operators, so like slices, functions, and structure types with slices cannot be used for map keys, because they have referential semantics and cannot be compared.

For the value of the map, there is no limit, the slice of this in the key can not be used, is fully used in the value.

Using map

The use of maps is simple, and arrays are similar, array slices are indexed, and map is through keys.

12
 Make (map[string]int) dict["Zhang San"

In the example above, if the key 张三 exists, the value is modified, and if it does not exist, the key value pair is added.

The value of getting a map key is also simple, similar to storage, or given the example above.

1
Age: = dict["Zhang San"]

In Go map, if we get a value of a nonexistent key, it is also possible to return a value type of 0 value, so that we do not know whether there is a zero value of a key value pair, or that the key value pair does not exist. In this context, map provides a way for us to detect the existence of a key-value pair.

1
Age,exists: = dict["John Doe"]

Look at this example, and get the value of the key is not much different, just one more return value. The first return value is the value of the key, the second return value marks the existence of the key, which is a boolean variable of type, and we can tell it to know if the key exists. This is also the benefit of Go multi-value return.

If we want to delete a key-value pair from a map, we can use the functions built into go delete .

1
Delete (Dict,"Zhang San")

deleteThe function accepts two parameters, the first is the map to be manipulated, and the second is the key of the map to be deleted.

The delete function removes the nonexistent key, but it does not have any effect.

If you want to traverse a map, you can use for range a style loop, just like traversing a slice.

1234
Map [string] int {"Zhang San"}  for Range dict {fmt. PRINTLN (key, Value)}

Here the range return two values, the first one is the map key, the second is the map of the key corresponding value. Here again, this traversal is unordered, that is, the key value pair will not appear according to the established data, if you want to go through the sequence, you can first sort the key in the map, and then traverse the sorted key, take the corresponding value out, see below an example to understand.

 1234567891011 
 func  main   ()   {dict: = map  [string ]< span class= "keyword" >int  {: 60 ,  "Zhang San" : 43 }var  names []string  for  name: = range  dict { names = append  (names, name)}sort. Strings (names) //sort  for  _, Key: =  Range  names {fmt. Println (Key, Dict[key])}} 

In this example, there is a trick, range a map, you can also use a return value, the default return value is the key of the map.

Passing a map between functions

Passing a map between functions does not copy a copy of the map, which means that if a map is passed to a function that modifies the map, then all references to the map will be aware of the change.

 123456789 
 func  main   ()   {dict: = map  [string ]int  {: 60 ,  "Zhang San" : 43 }modify (dict) fmt. Println (Dict[ "Zhang San" ])}func  modify   (dict map  []int )   {dict[ "Zhang San" ] = 10 } 

The result of the above example output is that it has been modified by the function to prove that the 10 pass is not a copy of the map. This feature is similar to slicing, so it is much higher because copying the entire map is too expensive.

"Go language Combat" reading notes, not to be continued, welcome to sweep code attention flysnow_org to the public, the first time to see follow-up notes.

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.