By default, Go copies values when you pass them around. But sometimes, that can be undesirable. For example, if you accidentally copy a mutex and multiple goroutines work on separate instances of the lock, they won’t be properly synchronized. In those cases, passing a pointer to the lock avoids the copy and works as expected.
Take this example: passing a sync.WaitGroup by value will break things in subtle ways:
func f(wg sync.WaitGroup) {
// ... do something with the waitgroup
}
func main() {
var wg sync.WaitGroup
f(wg) // oops! wg is getting copied here!
}
sync.WaitGroup lets you wait for multiple goroutines to finish some work. Under the hood,
it’s a struct with methods like Add, Done, and Wait to sync concurrently running
goroutines.