Strings Replace Zero
ID |
go.strings_replace_zero |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Go |
Tags |
reliability, suspicious |
Description
Reports a call to strings.Replace(s, old, new, 0) whose fourth argument — the replacement
count — is the literal 0. A count of 0 replaces nothing and returns the original string
unchanged, which is almost never the intent. To replace every occurrence the count must be
negative, idiomatically -1 (or strings.ReplaceAll).
Rationale
The count argument is easy to get wrong: 0 looks like "no limit" but actually means "make no
replacements". The result is a silent no-op — the returned string is identical to the input —
that produces wrong output without any error. Flagging the literal 0 surfaces the typo.
strings.Replace(s, "a", "b", 0) // FLAW — replaces nothing
strings.Replace(s, "a", "b", -1) // OK — replaces every occurrence
strings.Replace(s, "a", "b", 1) // OK — replaces the first occurrence
strings.ReplaceAll(s, "a", "b") // OK
Remediation
Use -1 to replace all occurrences (or strings.ReplaceAll), or a positive count to cap the
number of replacements.