On Sat, Feb 25, 2017 at 9:58 PM, Ayan George <a...@ayan.net> wrote: > > > On 02/25/2017 03:48 AM, Amit Saha wrote: >> >> I think both these approaches are fine, but just wanted to check. >> > > tl;dr: I think the second example is the way to go. > > I'm somewhat new to Golang so please someone correct me if I'm wrong. > > Neither of your examples are closures and, AFAIK, they're both > effectively the same. As Jan mentioned -- if you actually used a > closure like below, there *would* be a data race: > > func main() { > slice := []int{1, 23, 100, 101} > for _, val := range slice { > go func() { > fmt.Printf("val = %d\n", val) > }() > } > } >
Thanks for the reply. Yes, I have learned the same about issues with closures. Yes. indeed, my example #1 is using an anonymous function, not a closure. Jan mentioned though #2 has a race, and that got me confused. > Notice the goroutines access the same 'val' variable concurrently > while 'val' changes. > > I don't think your code presents a race because it copies 'val' when it > is passed as a parameter to printme() or to your anonymous function. > > I think the choice to use an anonymous function and the choice to use a > closure have their own considerations. > > You typically choose to use an anonymous function if the code > you want to execute is relatively short and if the code is something > that you don't plan to re-use. > > Your example is short but it is only one statement so wrapping it in an > anonymous function doesn't buy you anything. If it were two or three > statements I think it'd be worthwhile. Indeed, that makes sense. Thank you. > > -ayan > > -- > You received this message because you are subscribed to a topic in the Google > Groups "golang-nuts" group. > To unsubscribe from this topic, visit > https://groups.google.com/d/topic/golang-nuts/hFrnOexAw3o/unsubscribe. > To unsubscribe from this group and all its topics, send an email to > golang-nuts+unsubscr...@googlegroups.com. > For more options, visit https://groups.google.com/d/optout. -- http://echorand.me -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.