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.
To Copy a map use
for k,v := range originalMap {
newMap[k] = v
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.