There is nothing wrong with your original code, when you are doing os.Args[1:] you are creating a new slice which like any slice starts at index 0.
It's a matter of style (and performance) but you could also do this:
Copyfor index, arg := range os.Args {
if index < 1 {
continue
}
s += fmt.Sprintf("%d: %s", index, arg)
}
Answer from Franck Jeannin on Stack Overflowfor-range loop over slice in Go
Go loop indices for range on slice - Stack Overflow
Range over slice (element vs index) - Code Review - Go Forum
Go: Can you use range with a slice but get references? (iteration) - Stack Overflow
Videos
I'm relatively new to the language and would like to learn the nuances around for-loops over slice. In the sample below, even though I modify the range variable inside the loop, the loop only iterates over the original values - why is that? I do know that slices are a combination of pointer plus length but I cannot understand well enough yet the behavior of the loop evaluation.
func rangeTest(slice []int) (result []int) {
result = []int{}
for _, n := range slice {
if n%3 == 0 {
slice = append(slice, n*33)
}
result = append(result, n)
}
return result
}I tried finding documentation on the topic without much success.
https://go.dev/play/p/jQ7p2X-UqTY.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:
for i := range accounts {
a := &accounts[i]
a.balance = 100
// manipulate account A further...
}
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.
Just let the AccountList be []*Account. Then you'll get pointers to each Account inside the range.