Home >Backend Development >Golang >How to Convert a Slice of Strings to a Slice of String Pointers in Go?
Converting Slice of Strings to Slice of Pointers to Strings
The goal of this task is to transform a slice of strings into a slice containing pointers to each of those strings. Let's examine a specific example:
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)
Initial Confusion
It may seem counterintuitive that v, despite being a string, remains at the same memory address throughout the loop. This is because in this case, v is not a pointer to a string, but rather a copy of each string in values1.
Two Possible Solutions
Solution 1:
for i, _ := range values1 { values2 = append(values2, &values1[i]) }
This method correctly appends pointers to the elements in the original values1 slice to values2. However, it's important to note that values2 now contains addresses pointing directly to values1, so values1 will remain in memory as long as values2 exists.
Solution 2:
for _, v := range values1 { v2 := v values2 = append(values2, &v2) }
This alternative solution creates a temporary local variable (v2) for each iteration, assigns it the value of v, and then appends a pointer to v2 to values2. This ensures that values1 is independent from values2, and any modifications to values1 won't affect values2.
The above is the detailed content of How to Convert a Slice of Strings to a Slice of String Pointers in Go?. For more information, please follow other related articles on the PHP Chinese website!