Sort Slice Non Slice
ID |
go.sort_slice_non_slice |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Go |
Tags |
reliability, suspicious |
Description
Reports a sort.Slice or sort.SliceStable call whose first argument is a fixed-size array rather
than a slice. These functions reflect on their argument and panic at runtime with
sort.Slice of non-slice when it is not a slice.
Rationale
In Go an array [N]T is a distinct type from a slice []T, and sort.Slice only works on slices.
Passing an array is the classic mistake; the fix is to sort a slice that views the array, arr[:].
Because the resolved type system maps arrays and slices to the same kind, the check decides
array-vs-slice structurally and flags only two unambiguous cases: an array composite literal, and an
identifier that resolves to a variable declared with an explicit array type.
var arr [3]int = ...
sort.Slice(arr, less) // FLAW — arr is an array, not a slice
sort.Slice([5]int{}, less) // FLAW — array literal
sort.Slice(sl, less) // OK — sl is a slice
Remediation
Pass a slice to sort.Slice. To sort the elements of an array, slice it first: sort.Slice(arr[:],
less).