gpt4 book ai didi

pointers - 为什么在取消引用之前必须复制字符串?

转载 作者:行者123 更新时间:2023-12-01 21:16:58 25 4
gpt4 key购买 nike

要将值是字符串的映射转换为值是字符串的映射,我需要先复制字符串。如果我不同意,那么所有值都是相同的,可能是错误的值。为什么是这样?我不在这里使用字符串文字的地址。

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
}

最佳答案

函数v中只有一个变量mapConvert。应用程序将这个单个变量的地址用于映射中的每个键。

通过为循环的每次迭代创建一个新变量来进行修复。使用映射中变量的地址。

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

关于pointers - 为什么在取消引用之前必须复制字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61851951/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com