Golang gotchas: range operator
Programming Estimated reading time: ~2 minutes
If you iterate over a slice using the range operator you will get a copy of the value and not a pointer to it. This is also true for maps.
You can find more infos about this here. If you want to change the contents of the original slice you will have to access the slice using indices. I have prepared a small example below (run it at the Go Playground):
|
|
This is the output of the program:
Original struct content ---> [{Name:ORIGINAL}]
After calling alterStructWithRange() ---> [{Name:ORIGINAL}]
After calling alterStructWithRangeAndIdx() ---> [{Name:alterStructWithRangeAndIdx}]
A note about Netcup (advertisement)
Netcup is a German hosting company. Netcup offers inexpensive, yet powerfull web hosting packages, KVM-based root servers or dedicated servers for example. Using a coupon code from my Netcup coupon code web app you can even save more money (6$ on your first purchase, 30% off any KVM-based root server, ...).