Home > Software engineering >  Loop seems to be modifying a variable in Go
Loop seems to be modifying a variable in Go

Time:06-27

I have a variable decodedToken (type: struct), and I access one of its values called "Claims" through a type assertion:

claims := decodedToken.Claims.(jwt.MapClaims)

I then loop through the claims (type: map[string]interface{}), and modify its values in place:

  for key := range claims {
        claims[key] = "modified" key 
    }

Hence, I expect that the original decodedToken variable would be unchanged, since I have just performed an operation on the claims variable. However, decodedToken is also changed to my modified value.

My question is why is this so, and how do I leave the decodedToken untouched?

CodePudding user response:

Since claims is a reference type, like a map or slice.

The solution is make a deep copy of any referenced data. Unfortunately there are no universal way to make a deep copy of any map in Go. So you should make your own.

Or more practical way to do your job is making a new object(variable) to contain the modified decodedToken.

Also, it's not good to iterated a map and modify its value in a same statement.

  • Related