为什么golang行为中的字符串指针在范围循环中与直觉相反? [英] Why is string pointer in golang behavior counter-intuitive in range-loop?
本文介绍了为什么golang行为中的字符串指针在范围循环中与直觉相反?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用以下代码: https://play.golang.org/p/tCm1W-K-6ob
此代码将打印: [c c c]
,但 [a b c]
除外.
This code would print: [c c c]
, but [a b c]
is excepted.
type A struct {
a *string
}
func f() {
slist := []string{"a", "b", "c"}
list := make([]*A, len(slist))
for i, v := range slist {
item := &A{
a: &v,
}
list[i] = item
}
fmt.Printf("[%s %s %s]", *list[0].a, *list[1].a, *list[2].a)
}
func main() {
f()
}
为什么列表不是 ["a","b","c"]
?范围或& string
发生了什么事?
Why the list is not ["a", "b", "c"]
? What happened to the range or the &string
?
推荐答案
所有项均包含一个局部变量 v
的地址.
The items all contain the address of the one local variable v
.
如果您的目标是在 a
字段中分配slice元素的地址,请执行以下操作:
If your goal is to assign the address of the slice element the a
field, then do the following:
for i := range slist {
item := &A{
a: &slist[i], // address of element instead of local variable.
}
list[i] = item
}
您还可以通过在每次循环迭代中创建一个新变量来获得所需的输出:
You can also get the output you want by creating a new variable on each loop iteration:
for i, v := range slist {
v := v // create new value on each iteration.
item := &A{
a: &v,
}
list[i] = item
}
这篇关于为什么golang行为中的字符串指针在范围循环中与直觉相反?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文