当前位置:网站首页>Why are keys unordered in golang map
Why are keys unordered in golang map
2022-06-29 06:07:00 【Bald cat light King】
Golang Map Medium key Why is it out of order
Golang Easy to learnList of articles
One 、 Why is it out of order ?
Come to the point , First on the source code
func mapiterinit(t *maptype, h *hmap, it *hiter) {
// decide where to start
r := uintptr(fastrand())
if h.B > 31-bucketCntBits {
r += uintptr(fastrand()) << 31
}
mapiternext(it)
}
Go When we're traversing map when , It is not fixed to traverse from the first number , Each time, it starts from one position . Even one that will not change map, Just traverse it , It is also unlikely to return to a fixed order .
in other words ,GO Language proceeds from language Map Disorder of .
Two 、GO Why do you do this ?
In fact, it is mainly because of map After the expansion , There may be some key Move to new memory , Then this part is actually out of order . And the traversal process , In fact, it is to traverse memory addresses in order , At the same time, the memory addresses are traversed in order key. But it was already out of order .
Of course someone would say , If I were just one map, I promise not to map Perform operations such as modification and deletion , It is reasonable to say that there will be no change without capacity expansion . But also because of this ,GO In the source code
Add random elements , Traversal map Order randomization of , It is used to prevent users from traversing in sequence . And this is risky code , stay GO Under the strict grammatical rules of , It is strongly discouraged .
3、 ... and 、 Whether traversal is really disordered
1. First traversal
The code is as follows ( Example ):
package main
import "fmt"
func main() {
noSortMap := map[int]int{
1: 1,
2: 2,
3: 3,
4: 4,
5: 5,
6: 6,
}
for k, v := range noSortMap {
fmt.Println("key: ", k, "value: ", v)
}
}
It turned out just as expected , It doesn't start with the first number
2. Second traversal
Same code as above :
It turned out just as expected , Different from the first time
Four 、 How to get ordered key value pairs
We need to use section (Slice) To control ,
1. Detailed code
The code is as follows ( Example ):
package main
import (
"fmt"
"sort"
)
func main() {
noSortMap := map[int]int{
1: 1,
2: 2,
3: 3,
4: 4,
5: 5,
6: 6,
}
var noSortSlice []int
for k, v := range noSortMap {
noSortSlice = append(noSortSlice, k)
fmt.Println("key: ", k, "value: ", v)
}
fmt.Println(noSortSlice)
// Sort
sort.Ints(noSortSlice)
sortSlice := noSortSlice
fmt.Println(sortSlice)
for _, k := range sortSlice {
fmt.Println("key: ", k, "value: ", noSortMap[k])
}
}
First, the disordered key Put it in the slice
Then slice the disordered slices call sort Bag Ints Methods the sorting
After sorting, traverse the slice , The slices are now in order , be map The key value pairs of are also ordered
summary
Don't rely on map Traversal returns key The order , By randomly selecting the starting position of traversal, the return is out of order . If you want to get ordered key values , Please rely on ordered slices for access to get an effective order Map
I hope this blog will be beneficial to you . I am the light king , I represent myself. .边栏推荐
- Stack -- 739 Daily temperature
- 64 commonly used terms for data analysis, really all!
- Call the computer calculator and use it to convert several base numbers
- Est - ce que l'ouverture d'un compte de titres est sécurisée? Y a - t - il un danger?
- Two houses with different colors and the farthest distance
- How to use regex in file find
- QT writing map comprehensive application 58 compatible with multi browser kernel
- RTOS embarqués
- Blip: conduct multimodal pre training with cleaner and more diverse data, and the performance exceeds clip! Open source code
- DANGER! V** caught climbing over the wall!
猜你喜欢

2-nitro-5,10,15,20-tetra (4-methylphenyl) porphyrin copper (no2tmpp) Cu) /2-nitro-5,10,15,20-tetra (4-methylphenyl) porphyrin (no2tmpp) H2) Qiyue porphyrin supply

Leetcode simple problem building arrays with stack operation
![Meso tetra (4-N, N, n-trimethylaminophenyl) porphyrin (ttmapp) /meso tetra - [4- (BOC threonine) aminophenyl] porphyrin (TAPP thr BOC) supplied by Qiyue](/img/a9/0869c4f39a96cff63d1e310292c46d.jpg)
Meso tetra (4-N, N, n-trimethylaminophenyl) porphyrin (ttmapp) /meso tetra - [4- (BOC threonine) aminophenyl] porphyrin (TAPP thr BOC) supplied by Qiyue

5,10-di (4-aminophenyl) - 15,20-diphenylporphyrin (cis-dadph2) /5,15-di (4-aminophenyl) - 10,20-diphenylporphyrin (trans-dadph2) / (tri-apph2) supplied by Qiyue

Maximum ascending subarray sum of leetcode simple problem

Analysis report on the investment market of the development planning prospect of the recommended wind power industry research industry in 2022 (the attachment is a link to the network disk, and the re

2022 recommended tire industry research report industry development prospect market analysis white paper
![[C language series] - branch and loop statements](/img/bf/656c9189b4ab4387c5acab1c4a2804.jpg)
[C language series] - branch and loop statements

2-nitro-5,10,15,20-tetra (3,5-dimethoxyphenyl) porphyrin (no2tdmpp) H2) /5,10,15,20-tetra (4-methylphenyl) porphyrin (TMPP) H2) Qiyue porphyrin products

Openfpga wishes you a happy Lantern Festival!
随机推荐
Difference between parametric continuity and geometric continuity
Ghost in the Log4Shell
Installing modules in pycharm
Spark saving to external data source
QT precautions and RCC download address
Is it safe to open a securities account? Is there any danger
[chromium] win10 vs2019 environment chromium configuration and compilation.
Jenkins operation Chapter 5 trigger, configuration webhook, Jenkins parameterized construction
Design of leetcode simple problem goal parser
In 2022, I haven't found a job yet. I have been unemployed for more than one year. What is the "old tester" for eight years?
After nine years of testing, the salary for interviewing Huawei is 10000. Huawei employees: the company doesn't have such a low salary position
Why Houdini made the pyside2 plug-in crash
Difference between static and final
The translation of those exquisite lines in the eighth season of the big bang
2022.02.14
2022 recommended property management industry research report industry development prospect market investment analysis (the attachment is the link to the online disk, and the report is continuously up
Modularization and modular specification commonjs
HTTP Caching Protocol practice
Programming specification and variables of shell script
Kubernetes backup disaster recovery service product experience tutorial



