Use copy

ID

go.use_copy

Severity

info

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Best Practice

Language

Go

Tags

best-practice, code-style

Description

Reports a range loop whose entire body copies one slice into another element by element, dst[i] = src[i].

Rationale

The builtin copy(dst, src) performs exactly this copy in a single bounds-checked call backed by memmove, so it is both faster and clearer than the manual loop. The loop form also invites off-by-one and wrong-variable mistakes that copy removes entirely. Loops that transform elements, reverse the index, or do more than the plain copy are left untouched.

// Bad
for i := range src {
    dst[i] = src[i]
}

// Good
copy(dst, src)

Remediation

Replace the loop with copy(dst, src). Note that copy copies min(len(dst), len(src)) elements and returns that count, which matches the loop’s behaviour when dst is sized to src.

References