将一个地图的副本赋值给另一个似乎会修改原始地图。

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

Assigning to copy of a map seems to be modifying the original

问题

我有一个变量decodedToken(类型为struct),我通过类型断言访问它的一个名为"Claims"的值:

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

然后,我循环遍历claims(类型为map[string]interface{}),并直接修改它的值:

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

因此,我期望原始的decodedToken变量不会改变,因为我只是对claims变量进行了操作。然而,decodedToken也被修改成了我修改后的值。

我的问题是为什么会这样,以及如何保持decodedToken不变?

英文:

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?

答案1

得分: 1

由于claims是一个引用类型,类似于map或slice。

解决方案是对任何引用数据进行深拷贝。不幸的是,Go语言没有一种通用的方式来深拷贝任何map。所以你需要自己实现。

或者更实际的做法是创建一个新的对象(变量)来存储修改后的decodedToken

另外,在同一语句中迭代一个map并修改其值是不好的做法。

英文:

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.

huangapple
  • 本文由 发表于 2022年6月27日 12:29:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/72767007.html
匿名

发表评论

匿名网友

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

确定