英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论