问题
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
}
回答1:
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
}
See https://golang.org/doc/faq#closures_and_goroutines for an explanation of the same problem in the context of concurrency.
来源:https://stackoverflow.com/questions/61851951/why-must-i-copy-string-before-dereferencing