当前位置:网站首页>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. .边栏推荐
- Summary of redis basic knowledge points
- Personal blog item: processing of reading number +1 after viewing article details
- HTTP Caching Protocol practice
- Rearrangement string of leetcode simple question
- 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
- What are the uses of static?
- What has urbanization brought to our mental health and behavior?
- Test Development - ten years of sharpening one sword (VII) interface test tool postman
- 2022.02.14
- How to use regex in file find
猜你喜欢

Will the order of where conditions in MySQL affect the union index? Will where 1 =1 affect the use of the index? Does where 1 =1 affect the use of indexes?

JIRA basic usage sharing

Internet enterprises need CRM software to help

Meta metauniverse female safety problems occur frequently. How to solve the relevant problems in the metauniverse?

Output various graphics and text on the console through C #

Agile invincible event

The most complete machine learning model training process

Jenkins operation Chapter 6 mail server sending build results

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?

Test Development - ten years of sharpening one sword (VII) interface test tool postman
随机推荐
Hyperledger Fabric 2. X custom smart contract
Can redis implement hot standby?
[high concurrency] deeply analyze the callable interface
Week 10 - task 3- from point to circle to cylinder
Jenkins operation Chapter 5 trigger, configuration webhook, Jenkins parameterized construction
Regular expressions for shell script values
QT precautions and RCC download address
Analysis of ArrayList set in teacher Yang's class
[high concurrency] deeply analyze the callable interface
Monitor employee turnover dynamics. This system makes employees tremble!
Creation of Arduino uno development environment
Rich material libraries make modeling easy and efficient for developers
Summary of redis basic knowledge points
Alphacode made its debut! The programming version of "Alpha dog" competed quietly and defeated half of the programmers
Clickhouse data type
β- Tetraphenyl nickel porphyrin with all chlorine substitution| β- Thiocyano tetraphenyl porphyrin copper| β- Dihydroxy tetraphenyl porphyrin 𞓜 2-nitroporphyrin | supplied by Qiyue
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
Top ten Devops best practices worthy of attention in 2022
Servlet version conflict causes page 404
51 lines of code, self-made TX to MySQL software!



