英文:
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, &acl)
}
desiredAcls := make([]*kafkav1alpha2.Acl, 0)
for _, acl := range instance.Spec.Authorization.Acls {
cpyAcl := acl
desiredAcls = append(desiredAcls, &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<Object> acls = new ArrayList<>();
List<Object> desiredAcls = new ArrayList<>();
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论