当前位置:网站首页>The problem that all values are the same occurs after golang for range traverses and assigns values to the dictionary
The problem that all values are the same occurs after golang for range traverses and assigns values to the dictionary
2022-07-24 00:59:00 【Sindweller5530】
for range After traversing and assigning values to the dictionary, there is a problem that all values are the same
Let's look at this first ( Very classic ) The wrong sample :( For convenience json Package printout structure , I used the export field starting with an uppercase letter )
m := make(map[string]*student)
stus := []student{
{
Name: " name 1", Age: 1},
{
Name: " name 2", Age: 2},
{
Name: " name 3", Age: 3},
}
for _, stu := range stus {
m[stu.Name] = &stu
}
for k, v := range m {
fmt.Println(k, ":", v.Name)
}
Output results :
name 3 : name 3
name 1 : name 3
name 2 : name 3
- If you print in a loop
stu, You will find that every time you traverse stu The output of is normal , That is, it does traverse the elements at the corresponding position of the array - But when traversing to the next element , The corresponding value of the previous element in the dictionary will also become the value of this traversal element
- Last all keys mapping The value of is the same —— That is, the last element traversed
for range Is to create a copy of each element and then map the copy , It does not return a reference to an element , And the same traversal pointer is always used , This is no problem in circular reading . But if you loop through the hash table , Use the traversal pointer as the mapping of each key , Then the end of the loop will point to the last element , Cause all values to be the same . If we add printing
for _, stu := range stus {
m[stu.Name] = &stu
fmt.Println(m)
}
Output
map[ name 1:0xc00000c060 name 2:0xc00000c060 name 3:0xc00000c060]
It also shows these key Corresponding to the same memory address . Then the values in the natural dictionary are all the same .
There are two solutions :
- Use array index instead of traversal pointer
for i, v := range stus {
m[v.Name] = &stus[i]
}
Output
name 1 : name 1
name 2 : name 2
name 3 : name 3
- Create a new variable
for _, stu := range stus {
st := stu
m[stu.Name] = &st
}
The output is
name 1 : name 1
name 2 : name 2
name 3 : name 3
Reference resources
- https://studygolang.com/articles/9701
- https://draveness.me/golang/docs/part2-foundation/ch05-keyword/golang-for-range/
边栏推荐
- scroll-view实现下拉刷新(避免onload进入页面初始refresher-triggered为true触发下拉问题)
- Chapter 1 water test --*offer
- Dynamic rip configuration
- T-seda code
- Solve the error: uncaught (in promise) navigationduplicated: avoided redundant navigation to current location:“
- 1000个Okaleido Tiger首发上线Binance NFT,引发抢购热潮
- [QNX Hypervisor 2.2用户手册]9.1 配置变量
- Graphic pipeline (I) post-processing stage alpha test template test depth test mix
- Semaphore
- Interviewer: if the order is not paid within 30 minutes after it is generated, it will be automatically cancelled. How to realize it?
猜你喜欢

An article teaches you the basic use of kubernetes

Small farmers also have big goals in the test, and the latest big bat interview summary (constantly updating...)

Bean Validation使用篇----05

SAP 实施项目中涉及到编程方式操作 Excel 的几种场景介绍

網絡系統實驗:ping不通的問題解决
![[the 83rd fortnight of leetcode]](/img/41/411dc235a34f9dde06a41323628648.png)
[the 83rd fortnight of leetcode]

T-seda code

QT入门篇(2.1初入QT的开始第一个程序)

Memory forensics nssctf otterctf 2018 (replay)

多源文件方式去访问全局变量的方式(extern用法)
随机推荐
Development of main applet for business card traffic near the map
T-seda code
Dark horse programmer - interface test - four day learning interface test - day 4 - postman reads external data files, reads data files, IHRM project practice, employee management module, adds employe
Prometheus+node exporter+grafana monitoring server system resources
Fpga:ov7725 camera displays images in rgb565 format through vga/hdmi
Network system experiment: solve the problem of Ping failure
XXL job realizes the code parsing of email sending warnings (line by line code interpretation)
Notes and Thoughts on the red dust of the sky (VI) due to lack
Use of crawler request library 2
Graphic pipeline (I) post-processing stage alpha test template test depth test mix
The postman test interface has 404 or 500 errors when the URL is configured correctly
Redis common commands
[QNX Hypervisor 2.2用户手册]9.1 配置变量
AVX instruction set accelerated matrix multiplication
Testers who have been employed for 3 months are facing employment confirmation. Leaders: 1 year of work experience is packaged into 5 years, and the probation period is eliminated
Error running ‘XXX‘: Command line is too long. Shorten command line for AudioTest or also ...
SAP 电商云 Spartacus UI Store 相关的设计明细
Linx link, first level directory, redirection, CP and MV
Tutorial on principles and applications of database system (039) -- MySQL query (I): syntax analysis of select command
Okaleido tiger NFT is about to log in to the binance NFT platform. Are you looking forward to it?