为什么我必须在取消引用之前复制字符串? [英] Why must I copy string before dereferencing?
问题描述
要将值为字符串的映射转换为值为指向字符串的映射,我需要先复制字符串.如果我不这样做,则所有值都相同,可能是错误的值.为什么是这样?我不是在这里取字符串文字的地址.
To convert a map whose values are strings into one whose values are points to string, I need to copy the string first. If I do not, all the values are the same, potentially wrong value. Why is this? I am not taking the address of a string literal here.
func mapConvert (m map[string]string) map[string]*string {
ret := make(map[string]*string)
for k, v := range m {
v2 := v[:]
ret[k] = &v2
// With the following instead of the last 2 lines,
// the returned map have the same, sometimes wrong value for all keys.
// ret[k]=&v
}
return ret
}
推荐答案
在函数 mapConvert
中有一个变量 v
.应用程序将这个单一变量的地址用于映射中的每个键.
There is a single variable v
in the function mapConvert
. The application uses the address of this single variable for every key in the map.
通过为循环的每次迭代创建一个新变量来修复.使用映射中变量的地址.
Fix by creating a new variable for each iteration of the loop. Use the address of the variable in the map.
func mapConvert (m map[string]string) map[string]*string {
ret := make(map[string]*string)
for k, v := range m {
v := v // create a new 'v'.
ret[k] = &v
}
return ret
}
请参阅 https://golang.org/doc/faq#closures_and_goroutines 了解说明并发上下文中的相同问题.
See https://golang.org/doc/faq#closures_and_goroutines for an explanation of the same problem in the context of concurrency.
这篇关于为什么我必须在取消引用之前复制字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!