To understand what is happening under the hood you must understand the pointer and value semantics of for range
construct in go.
It is clearly explained in this ardan labs article
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.
solved Copy array of strings to array of string pointers