strings.Replace or bytes.Replace is told to make no replacements

tx0/go:replace-count-zerodefaultwarningbug

What it finds

strings.Replace(s, "a", "b", 0): the last argument is how many replacements to make at most, so 0 makes none and the call returns s unchanged. -1, or ReplaceAll, replaces every match. bytes.Replace counts the same way.

The count must be the literal 0, and the function Replace of the package strings or bytes, resolved through the imports of the file. The fix writes -1, which changes what the call does, so it is unsafe.

From the rule's source, replace_count_zero.rs.

Example from the rule's tests
package p import (	"bytes"	"strings") func f(s string, b []byte, n int) (string, []byte) {	s = strings.Replace(s, "a", "b", 0)tx0 reports: strings.Replace with a count of 0 replaces nothing	b = bytes.Replace(b, []byte("a"), nil, 0)tx0 reports: bytes.Replace with a count of 0 replaces nothing	s = strings.Replace(s, "a", "b", -1)	s = strings.Replace(s, "a", "b", 1)	s = strings.Replace(s, "a", "b", n)	s = strings.ReplaceAll(s, "a", "b")	return s, b} func g(s string) string {	strings := replacer{}	return strings.Replace(s, "a", "b", 0)} type replacer struct{} func (replacer) Replace(s, a, b string, n int) string { return s }
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs in every tier. To turn it off for a project, set its level in tx0.toml:

tx0.toml
[rules]
"tx0/go:replace-count-zero" = "off"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/go:replace-count-zero] reason="..."

tx0 explain tx0/go:replace-count-zero shows the same in the terminal. Found a false positive? Report it.