Why must I copy string before dereferencing?

风格不统一 提交于 2021-01-29 22:22:42

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!