遍历结构数组的地址范围

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

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.

huangapple
  • 本文由 发表于 2014年9月9日 22:10:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/25746800.html
匿名

发表评论

匿名网友

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

确定