go build_error ai_generated true

error: go vet: assignment copies lock value: sync.WaitGroup contains sync.noCopy

ID: go/waitgroup-copied-by-value

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2024-08-11First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.18 active — — —
1.22 active — — —

Root Cause

Passing a sync.WaitGroup by value copies its internal state; the copy's Done never reaches the original's Wait, so Wait hangs or panics.

generic

中文

按值传递 sync.WaitGroup 会复制其内部状态;副本的 Done 不会影响原始的 Wait,导致 Wait 挂起或 panic。

Workarounds

  1. 98% success
    func worker(wg *sync.WaitGroup) {
        defer wg.Done()
    }
  2. 95% success
    type Pool struct { wg sync.WaitGroup }
    func (p *Pool) Add() { p.wg.Add(1) }

Dead Ends

Common approaches that don't work:

  1. 90% fail

    The copy shares no state; Done on the copy doesn't decrement the original counter, so Wait blocks forever.

  2. 85% fail

    The state is still split across two structs; the mutex does not merge them.