Fix

"assignment to entry in nil map" in Go

This error occurs because you are trying to assign a value to a map key without first initializing the map with `make`.

This error occurs because you are trying to assign a value to a map key without first initializing the map with make. In Go, a map variable is nil by default, and you cannot write to a nil map; you must allocate the underlying data structure before use.

To fix this, ensure you call make(map[KeyType]ValueType) before any assignment. If you are unsure whether the map is initialized, you can check if it is nil and initialize it on the fly, or simply initialize it at the point of declaration.

Here is a practical example showing the error and the fix:

package main

import "fmt"

func main() {
	// This will panic: assignment to entry in nil map
	var users map[string]string 
	users["alice"] = "admin" // Panic occurs here

	// Fix: Initialize the map before assignment
	users = make(map[string]string)
	users["alice"] = "admin"
	users["bob"] = "guest"

	fmt.Println(users)
}

If you need to handle cases where the map might be nil dynamically (e.g., inside a function receiving a map parameter), use a conditional check:

func addRole(m map[string]string, name, role string) {
	if m == nil {
		m = make(map[string]string)
	}
	m[name] = role
}

Alternatively, if you are defining the map in a struct or at the package level, initialize it immediately to avoid this issue entirely:

type Config struct {
	Settings map[string]int
}

// Correct: Initialize in the struct literal
cfg := Config{
	Settings: make(map[string]int),
}
cfg.Settings["timeout"] = 30

Remember that make is required for maps, slices, and channels, but not for structs or basic types. The compiler will not catch this at compile time because the variable type is correct; it is a runtime panic. Always verify your map is initialized before writing to it, especially when passing maps between functions where the caller might not have initialized them.