Go

Go

Made by DeepSource

Subsequent calls to Load and Delete on sync.Map should be replaced with LoadAndDelete GO-W4011

Bug risk
Major
Autofix

LoadAndDelete is a single atomic operation, unlike calling Delete after Load. This prevents a condition where the goroutine is preempted, and the key is deleted by another goroutine.

Bad practice

package main

import (
    "sync"
)

func foo(m *sync.Map, k any) {
    v, ok := m.Load(k)
    if ok {
        m.Delete(k)
        // ...
    }
}

Recommended

package main

import (
    "sync"
)

func foo(m *sync.Map, k any) {
    v, deleted := m.LoadAndDelete(k)
    if deleted {
        // ...
    }
}