Go: Can you use a range with a slice, but get links? (Iteration)

Say I want to change the value for all objects in an array. I like the range syntax much 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 } 

This did not work, since a is a copy of the records from AccountList, and therefore we only update the copy.

This works the way I need to:

 for a := range( accounts ) { accounts[a].balance = 100 } 

But this code has an additional search inside the for loop.

Is there a way to make an iterator that gets structure references in an AccountList?

+4
source share
2 answers

Just give the account Account [] * Account. Then you will get pointers to each account within the range.

+3
source

The problem is that using the first for / range loop, you get the value of struct in variable a . The second for the loop / range that you used solves the problem by directly accessing the memory in the slice.

However, you are incorrect in stating that in the second cycle there is an β€œadditional” search for the second cycle. The loop condition simply checks the cut length and increments the counter until it reaches the end. Then the accounts[a] expression will actually search for the array and directly manipulate the memory. If something, the second for the loop translates into fewer instructions, because it does not copy the contents of the structural value to the variable first.

I think you are worried about having to refer to accounts[i] every time. If you want to perform several manipulations with the account inside the for loop, I think the best way to solve it:

 for i := range accounts { a := &accounts[i] a.balance = 100 // manipulate account A further... } 

Another possible solution, as Mew suggested, is simply to have slice retention indicators. There are advantages to any of the ways to do this, but the dilemma is the same regardless of whether you are in C or Go. Go just has a little more syntactic sugar.

+3
source

Source: https://habr.com/ru/post/1339069/


All Articles