go – Can't create copy of variable of type map[int]Struct in another variable by just assigning one variable to another

huangapple go评论69阅读模式
英文:

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
}

huangapple
  • 本文由 发表于 2016年11月10日 19:09:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/40526118.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定