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.