英文:
go - Can't create copy of variable of type map[int]Struct in another variable by just assigning one variable to another
问题
我有一个地图:
cart := map[10033207:{10033207 3 425 126} 10012761:{10012761 4 40 0}]
我想在另一个变量tempCart
中创建cart
的副本,这样我就可以在我的函数中修改tempCart
以供临时使用。我希望cart
的值保持不变。
tempCart := cart
//一些操作,修改tempCart并使其成为
//map[10033207:{10033207 2 425 126} 10012761:{10012761 1 40 0}]
问题是,当我修改tempCart
时,一些方式cart
也被修改并变为与tempCart
相等。
稍后当我打印cart
的值时,我得到:
map[10033207:{10033207 2 425 126} 10012761:{10012761 1 40 0}]
而不是原始值map[10033207:{10033207 3 425 126} 10012761:{10012761 4 40 0}]
。
我无法理解其中的原因,并想知道如何创建cart
的副本的解决方案。
编辑:这个问题被标记为与“将一个地图复制到另一个地图”重复,但我知道如何将一个地图复制到另一个地图,我的主要问题是为什么我不能只将一个地图分配给另一个变量。为什么我必须在循环中复制它。
英文:
I have a Map :
cart := map[10033207:{10033207 3 425 126} 10012761:{10012761 4 40 0}]
I want to create copy of cart
in another variable tempCart
so that I can modify tempCart for temporary usage in my function. I want that cart value remains the same.
tempCart := cart
//some operation which modifies temp cart and make it
//map[10033207:{10033207 2 425 126} 10012761:{10012761 1 40 0}]
The problem is that when I modify tempCart
, somehow cart
is also getting modified and becomes equal
to tempCart
.
Later when I print value of cart
I get:
map[10033207:{10033207 2 425 126} 10012761:{10012761 1 40 0}]
and not the original value that is map[10033207:{10033207 3 425 126} 10012761:{10012761 4 40 0}]
.
I can't understand the reason behind it and want to know the solution of how to create a copy of cart
.
EDIT: This question has been marked as Duplicate to copy one map to another
But I knew how to copy one map to anothor, my prime question was why couldn't I just assign one map to another variable. Why do I have to copy it in a loop.
答案1
得分: 5
要复制一个 map,可以使用以下代码:
for k, v := range originalMap {
newMap[k] = v
}
这段代码会遍历原始的 map,将键值对复制到新的 map 中。
英文:
To Copy a map use
for k,v := range originalMap {
newMap[k] = v
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论