go-tools icon indicating copy to clipboard operation
go-tools copied to clipboard

SA5000 doesn't detect nil map assignments to struct fields

Open aanm opened this issue 5 months ago • 1 comments

Summary

The SA5000 check for "assignment to nil map" currently detects direct nil map assignments but misses assignments to nil map fields within structs, including nested struct fields.

Current Behavior

Staticcheck only detects case 1 but misses cases 2 and 3:

package main

type StructWithMap struct {
	Map map[string]string
}

type NestedStruct struct {
	Inner StructWithMap
}

func testNilMapAssignments() {
	// Case 1: Direct nil map assignment - ✅ DETECTED by staticcheck
	var m map[string]string
	m["key"] = "value" // staticcheck catches this (SA5000)

	// Case 2: Struct field nil map assignment - ❌ NOT DETECTED
	var swm StructWithMap
	swm.Map["key1"] = "value1" // staticcheck misses this

	// Case 3: Nested struct field nil map assignment - ❌ NOT DETECTED
	var ns NestedStruct
	ns.Inner.Map["key2"] = "value2" // staticcheck misses this

	// Case 4: Initialized map (should NOT be detected)
	m2 := make(map[string]string)
	m2["key"] = "value"

	// Case 5: Map literal (should NOT be detected)
	m3 := map[string]string{"existing": "value"}
	m3["key"] = "value"
}

Test Results

Running staticcheck test-nilmap.go only reports:

test-nilmap.go:14:2: assignment to nil map (SA5000)

It misses the struct field assignments on lines 18 and 22.

Expected Behavior

SA5000 should detect all three cases of nil map assignments:

  1. Direct nil map assignments ✅ (already works)
  2. Assignments to nil map fields in structs ❌ (missing)
  3. Assignments to nil map fields in nested structs ❌ (missing)

Cases 4 and 5 should correctly NOT be flagged since those maps are properly initialized.

Runtime Behavior

All three problematic cases cause the same runtime panic:

panic: assignment to entry in nil map

Environment

  • Go version: go1.23.4
  • Staticcheck version: (staticcheck 2025.1.1 (0.6.1))
  • Operating System: Linux

aanm avatar Aug 05 '25 12:08 aanm

This happens because SA5000, like most other checks, operates at the variable level and does not decompose structs into their individual fields. This may get fixed in the future, but is not currently a priority.

dominikh avatar Aug 05 '25 16:08 dominikh