Answer the question
In order to leave comments, you need to log in
Are there pitfalls in using Golang references in goroutines?
Hello. I have code where I iterate over the elements in a list, using those elements in a goroutine that I run inside a loop. I want to safely pass a value to a goroutine, but I discovered a feature that if you pass a reference to a goroutine, the goroutine will have the most recent value of the variable in the loop (if enough time has passed and the loop has completed before the reference is accessed).
Is that how it should be? Are there any other points I should be aware of? Would it then be sufficient to simply not use references in loops, or is there something else to be aware of?
Code - https://play.golang.com/p/5phJY4x5Yaf
As a result of the code execution, it will be seen that in the case of using links - under each i 0 will be displayed - the value of the last element in the list. If there are no links, then everything is ok.
Answer the question
In order to leave comments, you need to log in
but I discovered a feature that if you pass a link to a goroutine, the goroutine will have the most recent value of the variable in the loopit's not a 'feature', it's the main feature of links. In any JAP.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question