Go for C# developers: the foreach is not what it seem to be

If you are learning Go you know there is no foreach nor while in Go - just for with a few different ways of setting it up. There is a nice gotcha if you are doing what you think is a foreach though.

If you look at the following code where the attempt is to calculate the sum of all items in a list of integers. What will the result be?
If you are not used to Go you might be surprised to hear that the result is 6... You can try it for yourself here. The reason is that in Go, the range function will return a range of indexes rather than the items themselves. Unless you use the variant of range that returns a tuple of index and value. You can see that in action here (where the index is ignored using an underscore variable).

While this behavior can lead to some really nasty bugs when you enumerate lists of integers you are more likely to just encounter compilation errors as you would use the index variable in a context where there should be an item of a different type at which point this feature of Go merely becomes annoying as you need to add that extra underscore...

No comments:

Post a Comment