当前位置:网站首页>golang for range遍历并赋值给字典后出现所有值相同的问题
golang for range遍历并赋值给字典后出现所有值相同的问题
2022-07-23 05:45:00 【Sindweller5530】
for range遍历并赋值给字典后出现所有值相同的问题
先看这段(非常经典的)错误示例:(为了方便用json包打印输出结构体,我使用了大写字母开头的导出字段)
m := make(map[string]*student)
stus := []student{
{
Name: "名字1", Age: 1},
{
Name: "名字2", Age: 2},
{
Name: "名字3", Age: 3},
}
for _, stu := range stus {
m[stu.Name] = &stu
}
for k, v := range m {
fmt.Println(k, ":", v.Name)
}
输出结果:
名字3 : 名字3
名字1 : 名字3
名字2 : 名字3
- 如果在循环中打印
stu,会发现每次遍历时stu的输出都是正常的,也就是确实遍历到了数组相应位置的元素 - 但是遍历到下一个元素时,上一个元素在字典中对应的值也将变为本次遍历元素的值
- 最后所有键mapping的值都为同一个——也即最后遍历到的元素
for range 是创建了每个元素的副本然后映射该副本,并不是返回对元素的引用,而且使用的一直是同一个遍历指针,这在循环读取中是没有问题的。但如果循环建立哈希表,使用遍历的指针作为每个键的映射,那么循环结束后会指向最后一个元素,造成所有的值都是同一个。如果我们在其中加入打印
for _, stu := range stus {
m[stu.Name] = &stu
fmt.Println(m)
}
输出
map[名字1:0xc00000c060 名字2:0xc00000c060 名字3:0xc00000c060]
也表明了这几个key所对应的是同一个内存地址。那么自然字典中的值都是同一个了。
解决方案有两种:
- 使用数组索引来代替遍历指针
for i, v := range stus {
m[v.Name] = &stus[i]
}
输出
名字1 : 名字1
名字2 : 名字2
名字3 : 名字3
- 创建新的变量
for _, stu := range stus {
st := stu
m[stu.Name] = &st
}
输出也是
名字1 : 名字1
名字2 : 名字2
名字3 : 名字3
参考
- https://studygolang.com/articles/9701
- https://draveness.me/golang/docs/part2-foundation/ch05-keyword/golang-for-range/
边栏推荐
- 1. Ten principles of Economics
- Blog building five: drawing bed selection
- Uni native plug-in development -- Youmeng one click login
- 【AUTOSAR CanDrive 2.了解通信Hoh、CanId与PduID的Mapping关系】
- 嵌入式从入门到精通(入土)——超详细知识点分享3
- 【AUTOSAR COM 3.信号的收发流程TX/RX】
- Doubts about using the incluxdb database
- 博客搭建四:将自己的博客加入百度和谷歌收录的方法
- 大小写字母转换
- Question bank of basic principles of steel structure
猜你喜欢

编码器的一点理解

【存储器了解 RAM flash和eeprom存储器的区别和作用】

钢结构基本原理试题及答案

Deep learning neural network

5.4 installation and use of pyinstaller Library

Navicat for MySQL 安装教程

Uni native plug-in development -- Youmeng one click login
![[CAN总线的物理层 ]1.CAN/CANFD采样的点的内容分享](/img/e4/0b709a6ed5e639a75e0506f6eac9fd.png)
[CAN总线的物理层 ]1.CAN/CANFD采样的点的内容分享

单片机学习笔记4--GPIO(基于百问网STM32F103系列教程)

【AUTOSAR DCM 1.模块简介(DSL,DSD,DSP)】
随机推荐
Navicat for MySQL 安装教程
配置TX1的系统 + 设为固态盘启动
博客搭建四:将自己的博客加入百度和谷歌收录的方法
Interpretation of the paper: iterative feature representation method to improve the prediction performance of N7 methylguanosine (m7G) sites
【AUTOSAR COM 2.通信协议栈进阶介绍】
常见排序--归并排序(递归和非递归)+计数排序
[AUTOSAR candrive 1. learn the function and structure of candrive]
Question bank of basic principles of steel structure
C语言数据库:基于tcp多进程的在线词典,有详细的步骤已经图解,欢迎大家来观看
表格个人简历
Axure实现增删改查
【分清楚常量指针与指针常量 Const int *与Int * Const的含义与用法】
求矩阵的鞍点及其对应的下标。
Switch implements expression evaluation
[AUTOSAR com 1. introduction to communication protocol stack]
嵌入式从入门到精通(入土)——超详细知识点分享3
【AUTOSAR CanDrive 1.学习CanDrive的功能和结构】
The CUDA version of pytorch installed by anconda is inconsistent with the CUDA version of the system
NLP natural language processing - Introduction to machine learning and natural language processing (2)
钢结构基本原理试题及答案