将字符串数组复制到字符串指针数组 [英] Copy array of strings to array of string pointers
问题描述
我正在尝试将字符串数组复制到字符串指针数组
I am trying to copy an array of strings into an array of string pointers
但是在范围的结尾,我看到目标数组中的所有元素都指向最后一个源数组中的元素。
but at the end of the range, I see that all elements in destination array are pointing to the last element in the source array.
我是新手,想正确了解引擎盖下发生的事情。
I am new to go and want to correctly understand what happening under the hood.
以下是代码段重现问题
emails := []string{"a", "b"}
CCEmails := []*string{}
for _, cc := range emails {
CCEmails = append(CCEmails,&cc)
}
fmt.Println(CCEmails)
https:// play.golang.org/p/i6zJqoA4qAc
推荐答案
要了解幕后情况,您必须了解用于范围
的指针和值的语义。
To understand what is happening under the hood you must understand the pointer and value semantics of for range
construct in go.
emails := []string{"a", "b"}
CCEmails := []*string{}
for _, cc := range emails {
p := &cc
fmt.Println(cc, p)
CCEmails = append(CCEmails,&cc)
}
以上代码遵循值语义。它复制原始切片并迭代切片内的值。在迭代时,它会复制指针处特定索引处的值。最后,指针指向迭代完成后的最后一个元素。
The above code follows the value semantics. It copies the original slice and iterates the values inside the slice. While iterating it copies the values at particular index at the pointer. Atlast, the pointer points to the last element after completion of iteration.
要获得所需的行为,请使用指针语义-
To get the desired behavior, please use pointer semantics -
emails := []string{"a", "b"}
CCEmails := []*string{}
for i := range emails {
CCEmails = append(CCEmails,&emails[i])
}
fmt.Println(CCEmails)
for i := range CCEmails {
fmt.Println(CCEmails[i], *CCEmails[i])
}
上面的代码遵循指针的语义。它在原始数组上循环,并将特定元素的地址附加到地址片中。
The above code follows pointer semantics. It loops on original array and appends the address of particular element into the address slice.
这篇关于将字符串数组复制到字符串指针数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!