0

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.

6
  • 1
    tempCart := cart is just assigning the reference of one struct to another. It is not "copying". There is no in-built way to copy structs in Go. You'll have to initialize the new struct with the values from the other one manually, or use a library like github.com/jinzhu/copier Commented Nov 10, 2016 at 11:11
  • Can't it be done somehow using pointers? Commented Nov 10, 2016 at 11:12
  • 4
    Possible duplicate of Why is a map value in one function affected by an entry to the map in another function? Also related: Copying all elements of a map into another. Commented Nov 10, 2016 at 11:26
  • 1
    @Jagrati: You use pointers specifically to modify the values of the original Commented Nov 10, 2016 at 14:15
  • @icza thanks I went through the answers of those question. However, I asked this question because I didn't knew I should have searched my problem like that. Thanks anyway. Commented Nov 11, 2016 at 5:24

1 Answer 1

5

To Copy a map use

for k,v := range originalMap {
  newMap[k] = v
}
Sign up to request clarification or add additional context in comments.

1 Comment

This will not do a deep copy of the structs in the map.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.