/plushcap/analysis/cloudflare/a-go-gotcha-when-closures-and-goroutines-collide

A Go Gotcha: When Closures and Goroutines Collide

What's this blog post about?

The text discusses an issue with goroutines and closures in Go programming language. It explains how using goroutines to run concurrently can lead to unexpected results when sharing a single variable across multiple closures, as demonstrated by the output "10 10 10..." instead of numbers from 0 to 9. The solution provided is to create a new variable and pass it as a parameter to the function call within each goroutine, ensuring that each closure has its own copy of the variable. This issue is also mentioned in the Go FAQ.

Company
Cloudflare

Date published
March 25, 2015

Author(s)
John Graham-Cumming

Word count
380

Language
English

Hacker News points
3


By Matt Makai. 2021-2024.