Map Index Byte Slice

ID

go.map_index_byte_slice

Severity

low

Remediation Complexity

simple

Remediation Risk

low

Remediation Effort

low

Resource

Efficiency

Language

Go

Tags

CWE:1164, efficiency, suspicious

Description

Reports indexing a map with m[string(b)] where b is a []byte.

Rationale

The Go compiler special-cases the pattern m[string(byteSlice)] so the conversion does not allocate a new string — but only when the conversion appears directly in the index expression. Binding the converted key to a variable first (k := string(b); m[k]) defeats the optimisation. The rule flags the direct, efficient form so that it is recognised and kept inline; it fires only when the base resolves to a map and the key is a string(…​) conversion of an unnamed []byte.

func fn(m map[string]int, b []byte) {
    _ = m[string(b)] // FLAW — keep the conversion inline, do not bind it to a variable
}

Remediation

Keep the string(byteSlice) conversion inline inside the index expression rather than assigning it to an intermediate variable.