Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the internal implementation and basic functions of Go language mapping?

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the "Go language mapping internal how to achieve and what are the basic functions", in the daily operation, I believe that many people in the Go language mapping internal how to achieve and what basic functions have doubts, the editor consulted all kinds of materials, sorted out simple and easy-to-use operation methods, hope to answer the "Go language mapping internal how to achieve and what basic functions" doubt helpful! Next, please follow the editor to study!

Internal implementation and basic functions of mapping

Mapping is a data structure used to store a series of unordered key-value pairs. Analogy to the dictionary in Map,Python in Java can be understood as an array-like data structure indexed by hash values and expected to be indexed within a certain range of continuous memory.

Values are stored based on keys in the mapping. The powerful feature of mapping is the ability to quickly retrieve data based on keys. A key, like an index, points to the value associated with the key.

Internal implementation

A map is a collection that iterates over the elements of the map in a manner similar to that of arrays and slices. But the mapping is an unordered collection, and the reason for the disorder is that the implementation of the mapping uses a hash table.

The mapped hash table contains a set of buckets.

When storing, deleting, or looking for key-value pairs, all operations must first select a bucket. Pass the key specified during the operation mapping to the mapped hash function, and the corresponding bucket can be selected.

The purpose of this hash function is to generate an index that eventually distributes key-value pairs among all available buckets. For Go language mappings, part of the generated hash key, specifically LOB, is used to select buckets.

The internal implementation of the bucket. Mapping uses two data structures to store data

The first is an array, which internally stores the high octet value of the hash key used to select the bucket. Used to distinguish which item of each key-value pair is to be stored in the bucket. The second is a byte array that stores key-value pairs. The byte array first stores all the keys in the bucket, and then stores all the values in the bucket. The storage of this key-value pair is designed to reduce the amount of memory required for each bucket.

With the increase of mapping storage, the more uniform the index distribution is, the faster the access key-value pair is. With the increase of mapping storage, the more uniform the index distribution is, the faster the access key-value pair is. Mapping balances the distribution of key-value pairs through a reasonable number of buckets.

Create and initialize

There are many ways in the Go language to create and initialize mappings, either using the built-in make function or using mapping literals.

Package mainimport ("fmt") func main () {/ / create a mapping with a key of type string and a value of type int dict: = make (map [string] int) / / create a mapping The type of key and value is string / / initialize the mapping dict_ with two key-value pairs: = map [string] string {"Red": "# da1337", "Orange": "# e95a22"} fmt.Println (dict) fmt.Print (dict_)} = map [] map [Orange:#e95a22 Red:#da1337]

When creating a mapping, a more common method is to use the mapping literal. The initial length of the mapping is determined based on the number of key-value pairs specified at initialization.

The mapped key can be any value. The type of this value can be either a built-in type or a structural type, as long as the value can be compared using the = = operator

Slices, functions, and structural types containing slices cannot be used as mapped keys because of their referential semantics. Using these types will result in compilation errors.

Package mainimport ("fmt") func main () {/ / create a mapping Key dict: = map [[] string] int {} fmt.Println (dict)} = [Running] go run "d:\ GolandProjects\ code-master\ demo\ hello.go" # command-line-argumentsdemo\ hello.go:10:45: duplicate key "Red" in map literal previous key at demo\ hello.go:10: 28 [done] exited with code=2 in 0.902 seconds

Declare a mapping that stores string slices

/ / create a mapping, using string slices as the value dict: = map [int] [] string {} use the mapping

Assigning a key-value pair to a mapping is done by specifying a key of the appropriate type and assigning a value to the key

Assign a value to a mapping

/ / create an empty mapping to store the color and the hexadecimal code corresponding to the color colors: = map [string] string {} / / add the Red code to the mapping colors ["Red"] = "# da1337"

You can create a mapping with a value of nil by declaring an uninitialized mapping, which cannot be used to store key-value pairs.

/ / create an empty mapping to store the color and the hexadecimal code corresponding to the color colors: = map [string] string {} / / add the Red code to the mapping colors ["Red"] = "# da1337"

There are two choices when taking values from the mapping:

The first option is to get both the value and a flag indicating whether the key exists or not

Get the value from the mapping and determine whether the key exists

/ / get the value corresponding to the key Blue value: = colors ["Blue"] / / does this key exist? If value! = "" {fmt.Println (value)}

Another option is to return only the value corresponding to the key, and then determine whether the key exists by determining whether the value is zero or not

Get a value from the mapping and determine whether the key exists by that value

/ / get the value corresponding to the key Blue value: = colors ["Blue"] / / does this key exist? If value! = "" {fmt.Println (value)}

In the go language, when a mapping is indexed by a key, a value is always returned even if the key does not exist. In this case, the zero value of the type corresponding to the value is returned

All values in an iterative map are the same as iterative arrays or slices, using the keyword range

Iterative mapping using range

/ / create a mapping Store the color and the hexadecimal code colors: = mapping [string] string {"AliceBlue": "# f0f8ff", "Coral": "# ff7F50", "DarkGray": "# a9a9a9", "ForestGreen": "# 228b22",} / / display all color for key in the mapping, value: = range colors {fmt.Printf ("Key:% s Value:% s\ n", key, value)} / / create a mapping Store the color and the hexadecimal code colors: = map [string] string {"AliceBlue": "# f0f8ff", "Coral": "# ff7F50", "DarkGray": "# a9a9a9", "ForestGreen": "# 228b22",} / / display all colors in the mapping for key, value: = range colors {fmt.Printf ("Key:% s Value:% s\ n", key, value)}

To remove a key-value pair from the mapping, use the built-in delete function

Remove an item from the mapping

/ / delete key-value pair delete (colors, "Coral") / / display all colors for key in the map, value: = range colors {fmt.Printf ("Key:% s Value:% s\ n", key, value)} / / delete key-value pair delete (colors, "Coral") / / display all color for key in the mapping Value: = range colors {fmt.Printf ("Key:% s Value:% s\ n", key, value)} passes mappings between functions

Passing a mapping between functions does not make a copy of the mapping. In fact, when a mapping is passed to a function and the mapping is modified, all references to the mapping are aware of the modification, which is similar to slicing and ensures that the mapping can be copied at a small cost

Package mainimport ("fmt") func main () {/ / create a mapping Store the color and the hexadecimal code colors: = map [string] string {"AliceBlue": "# f0f8ff", "Coral": "# ff7F50", "DarkGray": "# a9a9a9", "ForestGreen": "# 228b22",} / / display all colors in the mapping for key, value: = range colors {fmt.Printf ("Key:% s Value:% s\ n", key Value)} fmt.Println ("call function to remove the specified key") / / call the function to remove the specified key removeColor (colors, "Coral") / / display all colors for key in the map, value: = range colors {fmt.Printf ("Key:% s Value:% s Value:% s\ n", key, value)} / / removeColor deletes the key in the specified mapping func removeColor (colors map [string] string, key string) {delete (colors) Key)} package mainimport ("fmt") func main () {/ / create a mapping Store color and hexadecimal code colors: = map [string] string {"AliceBlue": "# f0f8ff", "Coral": "# ff7F50", "DarkGray": "# a9a9a9", "ForestGreen": "# 228b22" } / / display all colors in the map for key, value: = range colors {fmt.Printf ("Key:% s Value:% s\ n", key, value)} fmt.Println ("call function to remove specified key") / / call function to remove specified key removeColor (colors) "Coral") / / displays all colors for key in the map, value: = range colors {fmt.Printf ("Key:% s Value:% s\ n", key, value)}} / / removeColor deletes func removeColor (colors map [string] string, key string) {delete (colors) from the specified map Key)} [Running] go run "d:\ GolandProjects\ code-master\ demo\ hello.go" Key: Coral Value: # ff7F50Key: DarkGray Value: # a9a9a9Key: ForestGreen Value: # 228b22Key: AliceBlue Value: # f0f8ff calls the function to remove the specified key Key: AliceBlue Value: # f0f8ffKey: DarkGray Value: # a9a9a9Key: ForestGreen Value: # 228b22 [Done] exited with code=0 in 1.419 seconds

There is no capacity or any limit to the growth of the mapping. At the same time, the built-in function len can be used to obtain the length of slices or maps. But the built-in function cap can only be used for slicing.

At this point, the study of "how to implement the Go language mapping and what are the basic functions" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report