当前位置:网站首页>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. .边栏推荐
- 想问问,券商选哪个比较好尼?本人小白不懂,现在网上开户安全么?
- The simple problem of leetcode is to divide an array into three parts equal to sum
- QT precautions and RCC download address
- JS messagechannel transport
- Rich material libraries make modeling easy and efficient for developers
- AIRNET notes 1
- [C language series] - initial C language (4)
- Parsing rshub document auto generation API
- Analysis of ArrayList set in teacher Yang's class
- Meta metauniverse female safety problems occur frequently. How to solve the relevant problems in the metauniverse?
猜你喜欢

2,5-di (3,4-dicarboxyphenoxy) - 4 '- phenylethynylbiphenyldianhydride (pephqda) / Qiyue custom supply porphyrin modified amphiphilic block copolymer peg113-pcl46-porphyrin

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?

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

Use of sed in shell script

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

Design of leetcode simple problem goal parser

The fresh student who was born in Ali after 2000: it's really fragrant to mend this

Creation of Arduino uno development environment

Ti Click: quickly set up tidb online laboratory through browser | ti- team interview can be conducted immediately

QT writing map comprehensive application 58 compatible with multi browser kernel
随机推荐
ASP. Net core 6 framework unveiling example demonstration [03]:dapr initial experience
Loosely matched jest A value in tohavebeencalledwith - loose match one value in jest toHaveBeenCalledWith
Multiline regular expression search in Visual Studio code - multiline regular expression search in Visual Studio code
Review of MySQL knowledge points
HTTP Caching Protocol practice
The first commercial spacewalk of mankind is finalized! Musk SpaceX announced a new round of space travel plan, and the American rich became repeat customers
Parsing rshub document auto generation API
New d reflection generates ABI of C for class
Problems with MySQL database query
The translation of those exquisite lines in the eighth season of the big bang
Signal slot mechanism
Agile invincible event
Alphacode made its debut! The programming version of "Alpha dog" competed quietly and defeated half of the programmers
D Author: import C programming in D
Servlet version conflict causes page 404
Monitor employee turnover dynamics. This system makes employees tremble!
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
Analysis of ArrayList set in teacher Yang's class
Research Report on the recommended lithography industry in 2022 industry development prospect market investment analysis (the attachment is a link to the network disk, and the report is continuously u
Longest substring between two identical characters of leetcode simple question



