Modifying Map During Range Iteration

unpredictable behavior: new map entries may or may not appear during range iteration

Quick Answer

Adding or deleting map entries during range iteration is allowed but has unpredictable results for new entries. Collect changes and apply them after the loop.

Why This Happens

Go allows deleting map entries during range iteration and they will not appear in subsequent iterations. However, new entries added during iteration may or may not be visited. For predictable behavior, collect changes in a separate structure and apply them after the loop.

The Problem

func filterMap(m map[string]int) {
    for k, v := range m {
        if v < 0 {
            delete(m, k) // safe but confusing
        }
        m[k+"_copy"] = v // unpredictable: may or may not be visited
    }
}

The Fix

func filterMap(m map[string]int) {
    toDelete := []string{}
    toAdd := map[string]int{}
    for k, v := range m {
        if v < 0 {
            toDelete = append(toDelete, k)
        }
        toAdd[k+"_copy"] = v
    }
    for _, k := range toDelete {
        delete(m, k)
    }
    for k, v := range toAdd {
        m[k] = v
    }
}

Step-by-Step Fix

  1. 1

    Identify in-loop modifications

    Find map additions inside range loops that iterate over the same map.

  2. 2

    Collect changes separately

    Store additions and deletions in separate collections during iteration.

  3. 3

    Apply after the loop

    Apply all collected changes after the range loop completes.

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free