How to Use sync.Map in Go (Thread-Safe Map)

Use sync.Map for high-concurrency, read-heavy scenarios to avoid the performance penalty of locking a standard map.

Use sync.Map when you need a thread-safe map for high-concurrency read-heavy workloads without the overhead of a global lock. Initialize it with var m sync.Map and use Store, Load, and Delete methods for operations.

package main

import (
	"fmt"
	"sync"
)

func main() {
	var m sync.Map

	// Store a value
	m.Store("key", "value")

	// Load a value
	if val, ok := m.Load("key"); ok {
		fmt.Println(val) // Output: value
	}

	// Delete a value
	m.Delete("key")
}