## Overview

Staticcheck is a static analysis toolset for the Go programming language. It comes with a large number of checks, integrates with various Go build systems and offers enough customizability to fit into your workflows.

## Installation

There are various ways in which you can install staticcheck, but they all boil down to obtaining the command located at `honnef.co/go/tools/cmd/staticcheck`

If you use Go modules, you can simply run `go get honnef.co/go/tools/cmd/staticcheck` to obtain the latest released version. If you're still using a GOPATH-based workflow, then the above command will instead fetch the master branch. It is suggested that you explicitly check out the latest release branch instead, which is currently `2019.2`. One way of doing so would be as follows:

    cd $GOPATH/src/honnef.co/go/tools/cmd/staticcheck
    git checkout 2019.2
    go get
    go install

Alternatively, you can download pre-compiled binaries from GitHub.

If you'd like to be notified of new releases, you can use GitHub's Releases only watches.

## Running staticcheck

Staticcheck can be run on code in several ways, mimicking the way the official Go tools work. At the core, it expects to be run on well-formed Go packages. The most common way of specifying packages is via their import paths. One or more packages can be specified in a single command, and the `...` glob operator is supported. All of the following examples are valid invocations:

    staticcheck github.com/example/foo
    staticcheck github.com/example/foo github.com/example/bar
    staticcheck github.com/example/...

In addition, a single package can be specified as a list of files:

    staticcheck file1.go file2.go file3.go

Note that all files of the package need to be specified, similar to how `go build` works.

## Configuration

Various aspects of staticcheck can be customized with configuration files.

These files are placed in Go packages and apply recursively to the package tree rooted at the containing package. For example, configuration placed in `pkg` will apply to `pkg`, `pkg/subpkg`, `pkg/subpkg/subsubpkg` and so on.

Configuration files in subpackages can override or inherit from settings of configuration files higher up the package tree. Staticcheck's default configuration is represented as the virtual root of the configuration tree and can be inherited from.

### Configuration format

Staticcheck configuration files are named `staticcheck.conf` and contain TOML.

Any set option will override the same option from further up the package tree, whereas unset options will inherit their values. Additionally, the special value `"inherit"` can be used to inherit values. This is especially useful for array values, as it allows adding and removing values to the inherited option.

The special value `"all"` matches all possible values. Currently, this is only used when enabling checks.

Values prefixed with a minus sign, such as `"-S1000"` will exclude values from a list. This can be used in combination with `"all"` to express "all but", or in combination with `"inherit"` to remove values from the inherited option.

### Options

A list of all options and their explanations can be found on the Options page.

### Example configuration

The following example configuration is the textual representation of staticcheck's default configuration.

    {{ option "checks" }} = ["all", "-{{ check "ST1000" }}", "-{{ check "ST1003" }}", "-{{ check "ST1016" }}"]
    {{ option "initialisms" }} = ["ACL", "API", "ASCII", "CPU", "CSS", "DNS",
    	"EOF", "GUID", "HTML", "HTTP", "HTTPS", "ID",
    	"IP", "JSON", "QPS", "RAM", "RPC", "SLA",
    	"SMTP", "SQL", "SSH", "TCP", "TLS", "TTL",
    	"UDP", "UI", "GID", "UID", "UUID", "URI",
    	"URL", "UTF8", "VM", "XML", "XMPP", "XSRF",
    	"XSS"]
    {{ option "dot_import_whitelist" }} = []
    {{ option "http_status_code_whitelist" }} = ["200", "400", "404", "500"]

## Command-line flags

In addition to configuration files, some aspects of staticcheck can be controlled via command-line flags. These are settings that can vary between individual invocations or environments (CI, editors, ...) and shouldn't be stored in configuration files.

Flag | Description
--- | ---
-checks | Allows overriding the list of checks to run. Has the same syntax as the `checks` setting in configuration files.
-explain | Print the description of a check.
-f | Select between the different output formats.
-fail | Specify the list of checks which, if they find any issues in your code, should cause staticcheck to exit with a non-zero status. This can be used, for example, to not fail your CI pipeline because of possible code simplifications.
-go | Select the Go version to target. See Targeting Go versions for more details.
-show-ignored | Show all problems found, even those that were ignored by linter directives.
-tags | Similar to `go build -tags`, allows specifiying the build tags to use.
-tests | Include tests in the analysis.
-unused.whole-program | Run unused in whole program mode.
-version | Display the version of staticcheck and exit.

## Targeting Go versions

By default, staticcheck will make suggestions that are correct for the current version of Go. If you're wishing to support older versions of Go, not all suggestions are applicable – some simplifications are only valid for newer versions of Go and deprecated functions may not have had viable alternatives in older versions.

To target a specific Go version you can use the `-go` command line flag. For example, with `-go 1.6`, only suggestions that are valid for Go 1.6 will be made.

## Ignoring problems

In general, you shouldn't have to ignore problems reported by staticcheck. Great care is taken to minimize the number of false positives and subjective suggestions. Dubious code should be rewritten and genuine false positives should be reported so that they can be fixed.

The reality of things, however, is that not all corner cases can be taken into consideration. Sometimes code just has to look weird enough to confuse tools, and sometimes suggestions, though well-meant, just aren't applicable. For those rare cases, there are several ways of ignoring unwanted problems.

### Line-based linter directives

The most fine-grained way of ignoring reported problems is to annotate the offending lines of code with linter directives.

The `//lint:ignore Check1[,Check2,...,CheckN] reason` directive ignores one or more checks on the following line of code. The `reason` is a required field that must describe why the checks should be ignored for that line of code. This field acts as documentation for other people (including future you) reading the code.

Let's consider the following example, which intentionally checks that the results of two identical function calls are not equal:

    func TestNewEqual(t *testing.T) {
      if errors.New("abc") == errors.New("abc") {
        t.Errorf(`New("abc") == New("abc")`)
      }
    }

{{ check "SA4000" }} of staticcheck will flag this code, pointing out that the left and right side of `==` are identical – usually indicative of a typo and a bug.

To silence this problem, we can use a linter directive:

    func TestNewEqual(t *testing.T) {
      //lint:ignore SA4000 we want to make sure that no two results of errors.New are ever the same
      if errors.New("abc") == errors.New("abc") {
        t.Errorf(`New("abc") == New("abc")`)
      }
    }

#### Maintenance of linter directives

It is crucial to update or remove outdated linter directives when code has been changed. Staticcheck helps you with this by making unnecessary directives a problem of its own. For example, for this (admittedly contrived) snippet of code

    //lint:ignore SA1000 we love invalid regular expressions!
    regexp.Compile(".+")

staticcheck will report the following:

    tmp.go:1:2: this linter directive didn't match anything; should it be removed?

Checks that have been disabled via configuration files will not cause directives to be considered unnecessary.

### File-based linter directives

In some cases, you may want to disable checks for an entire file. For example, code generation may leave behind a lot of unused code, as it simplifies the generation process. Instead of manually annotating every instance of unused code, the code generator can inject a single, file-wide ignore directive to ignore the problem.

File-based linter directives look a lot like line-based ones:

    //lint:file-ignore U1000 Ignore all unused code, it's generated

The only difference is that these comments aren't associated with any specific line of code. Conventionally, these comments should be placed near the top of the file.

Unlike line-based directives, file-based ones will not be flagged for being unnecessary.

## Resource usage

Static analysis is a rather resource intensive process, having to apply expensive algorithms to a lot of data. Depending on the complexity of the checked code, this can result in many gigabytes of memory usage and minutes (if not hours) of CPU time.

To combat the time complexity of static analysis, staticcheck makes use of caching. It reuses Go's build cache as well as its own facts cache to avoid analysing dependencies whenever possible. In development environments, there is usually nothing to do to benefit from these caches. In CI, however, you have to ensure that the caches persist across successive runs of CI. The build cache and fact cache are stored beneath the `os.UserCacheDir()` directory, in `go-build` and `staticcheck` respectively. On Linux, by default, these directories can be found in `~/.cache/go-build` and `~/.cache/staticcheck`.

The overall memory consumption of staticcheck is controlled by the degree of parallelism. The more CPU cores a system has available, the more packages will be checked in parallel, increasing the total amount of memory needed. Staticcheck respects the `GOMAXPROCS` environment variable to control the degree of parallelism.

Note that reducing `GOMAXPROCS` only benefits systems with a lot of cores and code bases with a lot of packages. As `GOMAXPROCS` approaches 1, peak memory usage will be dominated by the most complex package in the code base. Additionally, smaller code bases may have such interconnected dependencies that peak parallelism is never reached, or there may simply be fewer packages than cores. For example, when checking 10 packages it makes no difference if GOMAXPROCS is set to 32 or 16, at most 10 packages can be processed in parallel.

Furthermore, a certain amount of type information per package needs to be retained until the end of the process, which means that overall memory usage grows with the number of checked packages. You can reduce this effect by disabling the U1000 and U1001 checks via the `-checks` command line flag (e.g. via `staticcheck -checks="inherit,-U1000,-U1001"`).

Finally, you can trade execution time for memory usage by setting the `GOGC` environment variable to a value less than 100. This will run more frequent garbage collection, potentially lowering peak memory usage, at the cost of spending more CPU.

## Checks

A list of all checks can be found on the Checks page.