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) }() } } 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. -ayan -- 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.