当前位置:网站首页>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. .边栏推荐
- Est - ce que l'ouverture d'un compte de titres est sécurisée? Y a - t - il un danger?
- Why can't the article be posted?
- 5- (4-benzoimide phenyl) - 10,15,20-triphenylporphyrin (battph2) and its Zn complex (battpzn) / tetra (4-aminophenyl) porphyrin (tapph2) Qiyue supply
- HTTP Caching Protocol practice
- The most complete machine learning model training process
- Test Development - ten years of sharpening one sword (VII) interface test tool postman
- Benign competition will promote each other
- Can redis implement hot standby?
- The translation of those exquisite lines in the eighth season of the big bang
- Functions and arrays of shell scripts
猜你喜欢

Call the computer calculator and use it to convert several base numbers

Manual (functional) test 1

The simple problem of leetcode is to divide an array into three parts equal to sum

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

Segment in Lucene

Analysis report on the investment market of the development planning prospect of the recommended rare earth industry research industry in 2022 (the attachment is a link to the online disk, and the rep
![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

2022 recommended quantum industry research industry development planning prospect investment market analysis report (the attachment is a link to the online disk, and the report is continuously updated

2022 recommended REITs Industry Research Report investment strategy industry development prospect market analysis (the attachment is a link to the online disk, and the report is continuously updated)

2022 recommended high-speed rail industry research report investment strategy industry development prospect market analysis (the attachment is a link to the online disk, and the report is continuously
随机推荐
Kubernetes backup disaster recovery service product experience tutorial
Can redis implement hot standby?
Love that can't be met -- what is the intimate relationship maintained by video chat
5,10,15,20-tetra (3,5-dimethoxyphenyl) porphyrin ((tdmpp) H2) /2-nitro-5,10,15,20-tetra (3,5-dimethoxyphenyl) porphyrin copper (no2tdmpp) Cu) supplied by Qiyue
Functions and arrays of shell scripts
Pytest (7) -yield and termination function
Mongodb basic knowledge summary
Two houses with different colors and the farthest distance
Week 10 - task 1- fill in the blank: line class inherits point class
Embedded RTOS
ES6 Modularization: export /import
Analysis report on the investment market of the development planning prospect of the recommended NFT industry research industry in 2022 (the attachment is a link to the online disk, and the report is
Purple red solid meso tetra (o-alkoxyphenyl) porphyrin cobalt (meso-t (2-rop) PCO) / tetra (n, n-diphenyl-p-amino) phenyl porphyrin (tdpatph2)
2,5-di (3,4-dicarboxyphenoxy) - 4 '- phenylethynylbiphenyldianhydride (pephqda) / Qiyue custom supply porphyrin modified amphiphilic block copolymer peg113-pcl46-porphyrin
2022 recommended high-speed rail industry research report investment strategy industry development prospect market analysis (the attachment is a link to the online disk, and the report is continuously
嵌入式RTOS
Loosely matched jest A value in tohavebeencalledwith - loose match one value in jest toHaveBeenCalledWith
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
The translation of those exquisite lines in the eighth season of the big bang
Sourcetree remote red exclamation point



