Go for C# developers: Closures, loops and pointers

As a seasoned C# developer you should be familiar with the common pitfalls of closures where a variable in a lambda function is not always what you think it is. Go's pointers can easily introduce a similar problem even without the use of lambdas.

The easiest way to accidentally run into this bug is if you enumerate over some collection of objects where your code needs to assign a pointer to that object to something else. Since the loop variable is declared in the for statement it will have the same address in each iteration of the loop. Here is an example of this in action.

When you think about it, this is obviously what should happen and your (or in this case my) code has a bug. But if you are new to Go you might be tempted to throw that ampersand on there just to make it compile with devastating results.

No comments:

Post a Comment