go runtime_error ai_generated true

WARNING: DATA RACE: Write by goroutine X, Read by goroutine Y (channel send/recv)

ID: go/goroutine-racy-channel-send-recv

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2026-06-30First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0 active
1.20 active

Root Cause

Sending a pointer to a struct via channel, then modifying the struct in sender while receiver reads it.

generic

中文

通过通道发送结构体指针,然后发送者在接收者读取时修改结构体。

Workarounds

  1. 95% success Send value instead of pointer
    ch := make(chan MyStruct)
    go func() {
        s := MyStruct{Field: 42}
        ch <- s // copy of s
    }()
    s := <-ch
  2. 85% success Use mutex to protect shared struct
    type Shared struct {
        mu sync.Mutex
        data MyStruct
    }
    var s Shared
    ch := make(chan *Shared)
    go func() {
        s.mu.Lock()
        s.data.Field = 42
        s.mu.Unlock()
        ch <- &s
    }()

Dead Ends

Common approaches that don't work:

  1. Assuming channel synchronization protects the data 90% fail

    Channel synchronizes the send/recv operation, not the data pointed to.

  2. Copying pointer before send 80% fail

    Copying pointer doesn't deep copy the struct; still shared.