在Go语言的for range语句中,为什么循环体变量的生命周期不限于单个循环?

huangapple go评论78阅读模式
英文:

In Go's for range statement, Why the life cycle of loop body variables doesn't limit to a single loop

问题

我是你的中文翻译助手,以下是翻译好的内容:

我刚开始接触Go语言,之前是Java开发者。最近我遇到了一个问题,就像下面的代码一样,第一个片段会导致赋值问题,而第二个则不会。

但是我不知道为什么。

desiredAcls := make([]*kafkav1alpha2.Acl, 0)
for _, acl := range instance.Spec.Authorization.Acls {
    desiredAcls = append(desiredAcls, &acl)
}

desiredAcls := make([]*kafkav1alpha2.Acl, 0)
for _, acl := range instance.Spec.Authorization.Acls {
    cpyAcl := acl
    desiredAcls = append(desiredAcls, &cpyAcl)
}

与Java不同,这里不会出现问题,我可以很自由地编写代码,因为循环体变量的生命周期仅限于单个循环。

List<Object> acls = new ArrayList<>();
List<Object> desiredAcls = new ArrayList<>();
for (Object acl : acls) {
   desiredAcls.add(acl);
}

那么为什么Go语言不将循环体变量的生命周期限制在单个循环中呢?这种优化可以减少工程师的很多编码负担。

英文:

I am new to Go and used to be a javaer. Recently I came along such a problem,like the code below, the first snippet will cause assignment problem while the second will not.

But I don't know why.

desiredAcls := make([]*kafkav1alpha2.Acl, 0)
for _, acl := range instance.Spec.Authorization.Acls {
	desiredAcls = append(desiredAcls, &amp;acl)
}

desiredAcls := make([]*kafkav1alpha2.Acl, 0)
for _, acl := range instance.Spec.Authorization.Acls {
	cpyAcl := acl
	desiredAcls = append(desiredAcls, &amp;cpyAcl)
}

In constrast to Java,there will be no problem and I am very free to write code cause the life cycle of loop body variables limits to a single loop.

List&lt;Object&gt; acls = new ArrayList&lt;&gt;();
List&lt;Object&gt; desiredAcls = new ArrayList&lt;&gt;();
for (Object acl : acls) {
   desiredAcls.add(acl);
}

So why doesn't golang limit the life cycle of loop body variables to a single loop? this kind of optimization can reduce a lot of coding burden for engineers.

答案1

得分: 3

> 但是我不知道为什么。

因为在第一个例子中,你正在获取一个指向循环变量的指针。每次迭代并不会创建一个新的变量,而是覆盖相同循环变量的值,所以每次迭代你都在获取指向相同内存的指针。

> 那为什么Go语言没有废除指针呢?

指针是有用的。但要真正回答这个问题,你需要问Go语言的设计者。

英文:

> But I don't know why.

Because in the first example, you're taking a pointer to the loop variable. Each iteration doesn't create a new variable, it overwrites the value of the same loop variable, so every iteration you're taking a pointer to the same memory.

> So Why didn't Go abolish Pointers?

Pointers are useful. But to really answer this question, you'd have to ask the Go language designers.

huangapple
  • 本文由 发表于 2021年8月10日 23:53:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/68729963.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定