I want to convert a slice of string into slice of pointer to string
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)
%!p(string=a) => string
%!p(string=b) => string
%!p(string=c) => string
[0xc42000e1d0 0xc42000e1d0 0xc42000e1d0]
From my understanding,
My variable v
seems to be a string, not a pointer to string.
Therefore v
should be copied from values1
when iterating.
Obviously I'm incorrect as v
still have the same address 0xc42000e1d0
.
How can v
value change if it's not a pointer?
For a quick solution use:
values1 := []string{"a", "b", "c"}
var values2 []*string
for i, _ := range values1 {
values2 = append(values2, &values1[i])
}