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

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

Patricia Arquette
Release: 2024-12-14 20:38:19
Original
569 people have browsed it

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

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

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

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!

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