The result of Index is compared with -1 or 0 only to learn whether a text contains another

tx0/go:index-for-containsstrictwarningstyle

What it finds

strings.Index(s, sub) != -1 asks for a position and throws it away; strings.Contains(s, sub) says what is meant. The same holds for IndexByte, IndexRune and IndexAny, whose counterparts are ContainsRune and ContainsAny, and for bytes.

The call must be one of those functions of strings or bytes, resolved through the imports, compared as != -1, >= 0, == -1 or < 0. The fix writes the matching Contains call, negated where needed, and is safe; for IndexByte, whose argument is a byte where Contains takes a string, no fix is offered.

From the rule's source, index_for_contains.rs.

Example from the rule's tests
package p import "strings" func f(s, sub string) bool {	if strings.Index(s, sub) != -1 {tx0 reports: this can be written as strings.Contains(s, sub)		return true	}	if strings.IndexRune(s, 'x') < 0 {tx0 reports: this can be written as !strings.ContainsRune(s, 'x')		return false	}	return strings.Index(s, sub) > 2}
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 from the strict tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/go:index-for-contains" = "warning"

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:index-for-contains] reason="..."

tx0 explain tx0/go:index-for-contains shows the same in the terminal. Found a false positive? Report it.