Ineffective Sort
ID |
go.ineffective_sort |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Code Smell |
Language |
Go |
Tags |
code-style, suspicious |
Description
Reports an assignment of the form x = sort.XSlice(x) — with sort.StringSlice, sort.IntSlice
or sort.Float64Slice — that re-assigns a slice to itself through one of the sort package’s view
types.
Rationale
sort.StringSlice, sort.IntSlice and sort.Float64Slice are types, not functions, so
sort.IntSlice(x) is a type conversion that produces a new value of the named slice type without
sorting anything. Assigning it straight back to x therefore sorts nothing — the author almost
certainly meant to sort x. The in-place helpers (sort.Ints, sort.Strings, sort.Float64s)
sort the slice directly; calling the view’s own Sort method (sort.IntSlice(x).Sort()) or using
sort.Sort(sort.IntSlice(x)) also sorts in place and is not reported. When x is already declared
as the matching view type the conversion is a harmless no-op rather than the sort-nothing mistake,
so that case is left alone.
// Bad
a = sort.StringSlice(a) // FLAW — conversion, sorts nothing
// Good
sort.Strings(a) // OK — direct in-place helper
sort.IntSlice(xs).Sort() // OK — the view's Sort method sorts in place
sort.Sort(sort.StringSlice(a)) // OK — sort.Sort sorts via the view
Remediation
Use the dedicated in-place helper (sort.Ints, sort.Strings, sort.Float64s), or sort the
slice through the view with sort.Sort(sort.XSlice(x)) or sort.XSlice(x).Sort().