英文:
range over addressess of struct array
问题
我有一个类型为[]Struct的结构体数组。当我以以下形式遍历它时:
for i, val := range mystructarray
我理解val是一个局部变量,它包含mystructarray[i]的副本。有没有比这更好的方法来遍历mystructarray的地址,而不是这样:
for i := range mystructarray{
valptr = &mystructarray[i]
}
?
英文:
I have a struct array of type []Struct. When I range over it in the form:
for i, val := range mystructarray
I understand that val is a local variable which contains a copy of mystructarray[i]. Is there a better way of iterating through the addressess of mystructarray than this:
for i := range mystructarray{
valptr = &mystructarray[i]
}
?
答案1
得分: 1
没有办法在接收切片内容的指针的同时进行迭代(除非当然,它是指针的切片)。
你的示例是最好的方式:
for i := range mySlice {
x = &mySlice[i]
// 使用 x 做一些操作
}
然而,请记住,如果你的结构体不是非常大,并且你不需要通过指针对它们进行操作,复制结构体可能会更快,并且能提供更清晰的代码。
英文:
There is no way to iterate while receiving a pointer to the contents of the slice (unless of course, it is a slice of pointers).
Your example is the best way:
for i := range mySlice {
x = &mySlice[i]
// do something with x
}
Remember however, if your structs aren't very large, and you don't need to operate on them via a pointer, it may be faster to copy the struct, and provide you with clearer code.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论