Skip to content

staticcheck: misuse of slice make() and append() #112

@cgilmour

Description

@cgilmour

A problem that seems to occur regularly is creating a slice with a length component, then only appending to it.
Example: https://play.golang.org/p/CehTV0VFKp

Generally, the intention would be making a zero-length slice with an initial capacity, then appending to it. The effect of this occurs only at runtime and the cause can be hard to spot when debugging and/or reading the related code -- it's a very subtle detail.

There may be cases where this was done intentionally to allocate some space for other functions to set the data, or to suit a particular protocol or data structure.
However, I expect that it's exceptionally rare compared to the common misuse.

A check that observes a slice created with make(slice-type, len) followed by only append()'s to that slice could be sufficient to detect the common mistake.

Metadata

Metadata

Assignees

No one assigned

    Labels

    aggressiveA set of checks that is more prone to false positives but is helpful during code reviewnew-check

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions