How to Convert a Slice of Strings to a Slice of Pointers to Strings
When working with slices of strings, it's often necessary to convert them to slices of pointers to strings. This allows you to access the underlying string values directly, rather than having to dereference them each time.
First Attempt
One approach to achieve this is to iterate over the slice of strings and append each string's address to a new slice. However, this doesn't work as expected because the loop variable v is assigned in each iteration, changing its value but not its address. As a result, you end up with a slice of pointers that all point to the same address.
values1 := []string{"a", "b", "c"} var values2 []*string for _, v := range values1 { fmt.Printf("%p | %T\n", v, v) values2 = append(values2, &v) } fmt.Println(values2) // Output: // %!p(string=a) => string // %!p(string=b) => string // %!p(string=c) => string // [0xc42000e1d0 0xc42000e1d0 0xc42000e1d0]
Correct Solution
To correctly create a slice of pointers to strings, you need to append the address of the proper slice element of the original slice:
for i := range values1 { values2 = append(values2, &values1[i]) }
In this case, the loop variable i is used to index into the original slice, ensuring that each address added to values2 corresponds to a unique string in values1.
Alternative Solution
An alternative solution is to create temporary local variables and append the addresses of those:
for _, v := range values1 { v2 := v values2 = append(values2, &v2) }
This approach is independent of the original slice and any modifications made to values1 will not affect values2.
The above is the detailed content of How to Correctly Convert a Slice of Strings to a Slice of Pointers to Strings in Go?. For more information, please follow other related articles on the PHP Chinese website!