将字符串切片转换为指向字符串的指针切片 [英] Convert slice of string to slice of pointer to string
问题描述
我想将字符串的一部分转换为指向字符串的指针的一部分
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)=>字符串
%!p(string = b)=>字符串
%!p(string = c)=>字符串
[0xc42000e1d0 0xc42000e1d0 0xc42000e1d0]
%!p(string=a) => string
%!p(string=b) => string
%!p(string=c) => string
[0xc42000e1d0 0xc42000e1d0 0xc42000e1d0]
据我了解,
我的变量v
似乎是一个字符串,而不是指向字符串的指针.
因此,v
应该在迭代时从values1
复制.
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.
显然我不正确,因为v
仍然具有相同的地址0xc42000e1d0
.
如果v
值不是指针,该如何更改?
Obviously I'm incorrect as v
still have the same address 0xc42000e1d0
.
How can v
value change if it's not a pointer?
使用以下快速解决方案:
values1 := []string{"a", "b", "c"}
var values2 []*string
for i, _ := range values1 {
values2 = append(values2, &values1[i])
}
推荐答案
第一个版本不起作用,因为只有一个循环变量v
,该变量在每次迭代中具有相同的地址 .在每次迭代中都会分配循环变量,该变量会更改其值,但不会更改其地址,并且您会在每次迭代中附加相同的地址.
The first version doesn't work as there is only one loop variable v
, which has the same address in each iteration. The loop variable is assigned in each iteration, which changes its value but not its address, and you append this same address in each iteration.
您建议的解决方案是:附加原始切片的适当切片元素的地址:
A possible solution is what you proposed: to append the address of the proper slice element of the original slice:
for i := range values1 {
values2 = append(values2, &values1[i])
}
这有效,但请注意,values2
包含指向values1
的后备数组的地址,因此values1
的后备数组将保留在内存中(不会收集垃圾),直到values1
和values2
变量不可访问.还要注意,修改values1
的元素将间接影响values2
,因为values2
的元素指向values1
的元素.
This works, but note that values2
contains addresses pointing to the backing array of values1
, so the backing array of values1
will be kept in memory (will not get garbage collected) until both values1
and values2
variables are unreachable. Also note that modifying elements of values1
will effect values2
indirectly, because elements of values2
point to elements of values1
.
另一种解决方案是创建临时局部变量并附加这些变量的地址:
Another solution is to create temporary local variables and append the addresses of those:
for _, v := range values1 {
v2 := v
values2 = append(values2, &v2)
}
这样做,您的values2
切片将不会阻止values1
收集垃圾,并且values1
中的修改值也不会反映在values2
中,它们将是独立的.
By doing this, your values2
slice will not keep values1
from getting garbage collected, also modifying values in values1
will not be reflected in values2
, they will be independent.
请参阅有关循环变量的相关问题:
See related questions about the loop variable:
这篇关于将字符串切片转换为指向字符串的指针切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!