go runtime_error ai_generated true

警告:数据竞争:协程X写入,协程Y读取(结构体字段)

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

ID: go/goroutine-racy-struct-field

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2026-03-05首次发现

版本兼容性

版本状态引入弃用备注
1.0 active
1.20 active

根因分析

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

English

Multiple goroutines accessing the same struct field without synchronization.

generic

解决方案

  1. 95% 成功率 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% 成功率 Use atomic.Value for struct
    var v atomic.Value
    v.Store(MyStruct{Field: 42})
    s := v.Load().(MyStruct)

无效尝试

常见但无效的做法:

  1. Using atomic operations on non-atomic types 70% 失败

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

  2. Copying struct before access 80% 失败

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