Range Over String

ID

go.range_over_string

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Code Smell

Language

Go

Tags

CWE:1164, code-style, readability

Description

Reports for _, r := range []rune(s) where the loop index is discarded.

Rationale

Ranging a string in Go already yields (byteIndex, rune) pairs, decoding UTF-8 on the fly, so the explicit []rune(s) conversion allocates a whole rune slice for nothing. Ranging the string directly is equivalent and avoids the allocation. When the index is named it is the rune-slice index, which differs from the byte index a direct string range would give, so that form is left alone.

func fn(s string) {
    for _, r := range []rune(s) { // FLAW — range over s directly
        println(r)
    }
    for _, r := range s { // OK
        println(r)
    }
}

Remediation

Range over the string itself instead of converting it to []rune first.