go runtime_error ai_generated true

WARNING: DATA RACE: Write by goroutine X, Read by goroutine Y (struct field)

ID: go/goroutine-racy-struct-field

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2026-03-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0 active
1.20 active

Root Cause

Multiple goroutines accessing the same struct field without synchronization.

generic

中文

多个协程在没有同步的情况下访问同一个结构体字段。

Workarounds

  1. 95% success Use mutex to protect struct field
    type Counter struct {
        mu sync.Mutex
        val int
    }
    func (c *Counter) Inc() {
        c.mu.Lock()
        c.val++
        c.mu.Unlock()
    }
  2. 85% success Use atomic.Value for struct
    var v atomic.Value
    v.Store(MyStruct{Field: 42})
    s := v.Load().(MyStruct)

Dead Ends

Common approaches that don't work:

  1. Using atomic operations on non-atomic types 70% fail

    atomic.AddInt64 works only on int64; other types need different approach.

  2. Copying struct before access 80% fail

    Copy doesn't prevent race; original struct still accessed.