Home > Backend Development > Golang > How to Correctly Convert a Slice of Strings to a Slice of Pointers to Strings in Go?

How to Correctly Convert a Slice of Strings to a Slice of Pointers to Strings in Go?

Linda Hamilton
Release: 2024-12-19 20:22:17
Original
709 people have browsed it

How to Correctly Convert a Slice of Strings to a Slice of Pointers to Strings in Go?

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]
Copy after login

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])
}
Copy after login

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)
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template