Go:您可以将范围与切片一起使用但获取引用吗? (迭代)
假设我想更改数组中所有对象的值。 我更喜欢范围语法,而不仅仅是命名为循环。
所以我尝试了:
type Account struct {
balance int
}
type AccountList []Account
var accounts AccountList
...
....
// to init balances
for _,a := range( accounts ) {
a.balance = 100
}
这不起作用,因为 a 是 AccountList 中条目的副本,因此我们仅更新副本。
这确实可以按照我的需要工作:
for a := range( accounts ) {
accounts[a].balance = 100
}
但是该代码在 for 循环内有一个额外的查找。
有没有办法创建一个迭代器来获取对 AccountList 中结构的引用?
Say I want to change a value for all objects in an array.
I like the range syntax a lot more than just named for loops.
So I tried:
type Account struct {
balance int
}
type AccountList []Account
var accounts AccountList
...
....
// to init balances
for _,a := range( accounts ) {
a.balance = 100
}
That did not work since a is a copy of the entries from the AccountList and we are thus updating the copy only.
This does work as I need it to:
for a := range( accounts ) {
accounts[a].balance = 100
}
But that code has an extra lookup inside the for loop.
Is there a way to do an iterator that gets references to the structs in the AccountList?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是,通过使用第一个 for/range 循环,您将按值获取变量
a
中的结构。您使用的第二个 for/range 循环通过直接访问切片中的内存来解决问题。但是,您指出第二个 for 循环内发生“额外”查找是错误的。循环条件只是检查切片的长度并增加计数器直到到达末尾。然后,accounts[a] 表达式将实际执行数组查找并直接操作内存。如果有的话,第二个 for 循环会转换为更少的指令,因为它不会首先将结构体的内容按值复制到变量中。
我认为您担心的是每次都必须引用
accounts[i]
。如果您想在 for 循环内对 Account 执行多次操作,我认为解决该问题的最佳方法如下:正如 Mue 所建议的,另一种可能的解决方案是简单地让切片保存指针。这两种方法都有优点,但无论您使用 C 还是 Go,困境都是一样的。 Go 只是多了一点语法糖。
The problem is that by using your first for/range loop, you are getting the struct by-value in the variable
a
. The second for/range loop you used solves the problem by accessing the memory in the slice directly.However, you are incorrect in stating that there is an "extra" lookup taking place inside the second for loop. The loop condition is merely going to examine the length of the slice and increment a counter until it hits the end. The
accounts[a]
expression will then actually perform an array lookup and manipulate the memory directly. If anything, the second for loop translates to less instructions because it isn't copying the contents of the struct by-value into a variable first.What I think you are worried about is having to reference
accounts[i]
every time. If you want to perform multiple manipulations on the Account inside the for loop, I think the best way to solve it would be like this:The other possible solution, as Mue suggested, is to simply have the slice hold pointers. There are advantages to either of the ways of doing this, but the dilemma is the same regardless of whether you are in C or Go. Go just has a little more syntactic sugar.
只需让 AccountList 为 []*Account 即可。然后您将获得指向范围内每个帐户的指针。
Just let the AccountList be []*Account. Then you'll get pointers to each Account inside the range.