WaitGroup.Add is called inside the goroutine it counts

tx0/go:waitgroup-add-in-goroutinedefaultwarningbug, concurrency

What it finds

go func() { wg.Add(1); ... }(): the counter is raised inside the goroutine it counts, so wg.Wait may run first and return before the goroutine has started.

wg must resolve to a variable or parameter declared in the file as a sync.WaitGroup or a pointer to one, by its type or by an initializer such as &sync.WaitGroup{} or new(sync.WaitGroup), with sync resolved through its import. Only an Add that is a statement of the goroutine's body itself is reported, and only when the body starts no goroutines of its own, which the Add could be counting.

From the rule's source, waitgroup_add_in_goroutine.rs.

Example from the rule's tests
package p import (	"sync"	s "sync") var shared sync.WaitGroup func run(items []int, done *sync.WaitGroup) {	var wg sync.WaitGroup	for range items {		go func() {			wg.Add(1)tx0 reports: wg.Add runs inside the goroutine it counts			defer wg.Done()		}()		wg.Add(1)		go func() {			defer wg.Done()		}()	}	go func() {		done.Add(1)tx0 reports: done.Add runs inside the goroutine it counts		done.Done()	}()	go func() {		shared.Add(1)tx0 reports: shared.Add runs inside the goroutine it counts		shared.Done()	}()	group := &s.WaitGroup{}	go func(g *sync.WaitGroup) {		group.Add(1)tx0 reports: group.Add runs inside		g.Add(1)tx0 reports: g.Add runs inside	}(group)	fresh := new(sync.WaitGroup)	go func() {		fresh.Add(1)tx0 reports: fresh.Add runs inside	}()	go func() {		wg.Add(len(items))		for range items {			go func() { defer wg.Done() }()		}	}()	go func() {		if len(items) > 0 {			wg.Add(1)		}	}()	wg.Wait()} type counter struct{ n int } func (c *counter) Add(n int) { c.n += n } func other() {	wg := &counter{}	go func() {		wg.Add(1)	}()	var wg2 struct{ Add func(int) }	go func() { wg2.Add(1) }()}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs in every tier. To turn it off for a project, set its level in tx0.toml:

tx0.toml
[rules]
"tx0/go:waitgroup-add-in-goroutine" = "off"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/go:waitgroup-add-in-goroutine] reason="..."

tx0 explain tx0/go:waitgroup-add-in-goroutine shows the same in the terminal. Found a false positive? Report it.