Use strings.Contains For Presence Tests

ID

go.use_contains

Severity

info

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Best Practice

Language

Go

Tags

best-practice, code-style

Description

Reports presence tests written as strings.Index(s, sub) != -1 or strings.Index(s, sub) >= 0. Both ask only whether sub occurs in s, which is exactly what strings.Contains(s, sub) expresses directly.

Rationale

strings.Index computes the byte offset of the first match. When that offset is immediately compared against -1 (or 0 with >=) the position is thrown away — only the yes/no answer matters. strings.Contains states that intent in one call, reads better, and removes the off-by-one trap of picking the wrong sentinel. The absence test (== -1) and genuine position comparisons are not reported.

// Bad
if strings.Index(s, sub) != -1 {
    handle()
}

// Good
if strings.Contains(s, sub) {
    handle()
}

Remediation

Replace strings.Index(s, sub) != -1 (or >= 0) with strings.Contains(s, sub).